假设你有这样一段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必须修改。
如果没有其他解决方案,我将不得不在我的生成器中传播更多的知识。但我更喜欢一种更简单的解决方案。
有什么想法吗?
提前谢谢。
发布于 2012-05-07 18:58:22
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;
}人们可以使用异常来做gotos,但是为了定位正确的“标签”,人们要么必须检查异常消息,要么必须考虑嵌套级别。
我不知道我是否觉得这不是更丑陋。
发布于 2012-05-07 18:58:47
您可以在标签前面的块周围添加一个虚拟循环,并使用标签为break的等价物goto:
public static Object doSmthg(Object A,Object B){
label:
do { // Labeled dummy loop
if(smthg){ //if is given has an example, it can be any thing else
doSmthg;
break label; // This brings you to the point after the labeled loop
}
doSmthg;
} while (false); // This is not really a loop: it goes through only once
dosmthg1(modifying A and B);
return an Object;
}发布于 2012-05-07 19:00:23
如果你想跳过某个东西,就像这样:
A
if cond goto c;
B
c: C你可以这样做
while (true) {
A
if cond break;
B
}
Chttps://stackoverflow.com/questions/10480722
复制相似问题