2

假设我有:

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

有什么方法可以做到这一点吗?

4

3 回答 3

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.");
}

如果无法更改 two(); 则可以添加未经检查的异常;

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.
}

你可以返回一个布尔值来表示返回,如果你可以改变 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.");
    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.");
    }
}
于 2011-04-02T08:01:10.850 回答
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;
}
于 2011-04-02T08:11:32.273 回答
1

查看您的代码,如果您调用 1,它会调用 2,后者调用 3 .. 如果您保持原样,那正是它会做的事情。两个(在你的一个)函数之后的行,只会在它从两个返回时完成,并且直到两个完成三个之后才会这样做。

于 2011-04-02T08:01:11.457 回答