如何在Java中打破/退出不同级别的方法调用

时间:2011-04-02 07:57:39

标签: java return exit break multi-level

让我说我有:

public void one() {
  two();
  // continue here
}
public void two() {
  three();
}
public void three() {
  // exits two() and three() and continues back in one()
}

有没有办法做到这一点?

3 个答案:

答案 0 :(得分:5)

没有更改方法two()的唯一方法是抛出异常。

如果您可以更改代码,则可以返回一个布尔值,告诉调用者返回。

然而,最简单的解决方案是将方法内联到一个更大的方法中。如果这个太大,你应该以另一种方式重新构建它,而不是在这样的方法之间放置复杂的控件。


说你有

public void one() {
    System.out.println("Start of one.");
    two();
// do something
    System.out.println("End of one.");
}

public void two() {
    System.out.println("Start of two.");
    three();
// do something
    System.out.println("End of two.");
}

public void three() {
    System.out.println("Start of three.");
// do something
    System.out.println("End of three.");
}

如果您无法更改两个();

,则可以添加未经检查的例外
public void one() {
    System.out.println("Start of one.");
    try {
        two();
    } catch (CancellationException expected) {
    }
// do something
    System.out.println("End of one.");
}

public void two() {
    System.out.println("Start of two.");
    three();
// do something
    System.out.println("End of two.");
}

public void three() {
    System.out.println("Start of three.");
// do something
    System.out.println("End of three.");
    throw new CancellationException(); // use your own exception if possible.
}

如果可以更改两个()

,则可以返回一个布尔值来表示返回
public void one() {
    System.out.println("Start of one.");
    two();
// do something
    System.out.println("End of one.");
}

public void two() {
    System.out.println("Start of two.");
    if (three()) return;
// do something
    System.out.println("End of two.");
}

public boolean three() {
    System.out.println("Start of three.");
// do something
    System.out.println("End of three.");
    return true;
}

或者你可以内联结构

public void one() {
    System.out.println("Start of one.");
    two();
// do something
    System.out.println("End of one.");
}

public void two() {
    System.out.println("Start of two.");
    System.out.println("Start of three.");
// do something for three
    System.out.println("End of three.");
    boolean condition = true;
    if (!condition) {
// do something for two
        System.out.println("End of two.");
    }
}

答案 1 :(得分:1)

查看你的代码,如果你打电话给它,它会调用两个,调用三个.. 如果你保持原样,那就完全是它的意思。两个(在你的一个)函数之后的行只会在它从两个回来后完成,并且它不会那样做直到两个完成三个...

答案 2 :(得分:1)

假设你可以改变two()方法,也许你想要这样的东西?

public void one() {
    two();
    // continue here from condition
}

public void two() {
    if (three()) {
        // go back due to condition 
        return;
    }

    // condition wasn't met
}

public boolean three() {
    // some condition is determined here

    if (condition) {
        // exits two() and three() and continues back in one()
        return true;
    }

    // condition wasn't met, keep processing here

    // finally return false so two() keeps going too
    return false;
}