gpt4 book ai didi

java - 臭名昭著的 Goto,Java,自动代码

转载 作者:行者123 更新时间:2023-12-04 05:47:38 25 4
gpt4 key购买 nike

想象一下,你有一个这样的 Java 代码:

public class MyClass {
public static Object doSmthg(Object A,Object B){
if(smthg){ //if is given has an example, it can be any thing else
doSmthg;
GOTO label;
}
doSmthg;

label;
dosmthg1(modifying A and B);
return an Object;
}
}

我正在自动生成代码。当生成器在生成 goto 的那一刻到达时(并且它不知道它在 if 块中),它不知道之后会发生什么。

我尝试使用标签、中断、继续,但这不起作用。

我尝试使用内部类(做 dosmthg1),但 A 和 B 必须声明为 final。问题是必须修改A和B。

如果没有其他解决方案,我将不得不在我的生成器中传播更多知识。但我更喜欢更简单的解决方案。

有什么想法吗?

提前致谢。

最佳答案

public static Object doSmthg(Object A,Object B){
try {
if(smthg){ //if is given has an example, it can be any thing else
doSmthg;
throw new GotoException(1);
}
doSmthg;

} catch (GotoException e) {
e.decrementLevel();
if (e.getLevel() > 0)
throw e;
}
dosmthg1(modifying A and B);
return an Object;
}

可以使用异常执行 goto,但是为了定位正确的“标签”,必须检查异常消息或考虑嵌套级别。

我不知道我是否觉得这不是更丑陋。

关于java - 臭名昭著的 Goto,Java,自动代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10480722/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com