infame Goto、Java、自动代码

infame Goto、Java、自动代码,java,code-generation,goto,labels,internal-class,Java,Code Generation,Goto,Labels,Internal Class,假设您有如下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

假设您有如下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;
}
一个人可以在有异常的情况下进行gotos,但是为了找到正确的“标签”,必须检查异常消息或考虑嵌套级别


我不知道我是否觉得这更难看。

您可以在标签前面的块周围添加一个虚拟循环,并使用带标签的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;
}

如果你想跳过什么东西,比如:

A
if cond goto c;
B
c: C
你可以这样做

while (true) {
    A
    if cond break;
    B
}
C

那么您想在Java代码生成器中实现一个
GOTO
?为什么?为什么不直接使用
if-else
?这样会一直执行一个不好的命令。Dasblinkenlight有一个更好的解决方案:
do{…}while(false)
。如果goto已经在一个循环中,这个解决方案需要代码生成器的知识(“if”作为一个例子给出)。使用fall-thru cases和
if(cond)break切换也很合适。这很难看,是的,但也很有创意明亮的我只需要在每个功能一个标签。我必须承认,我从未想到过使用异常来做这件事。糟糕的是,我不能投票支持你的职位。