Ham*_*lyn 2 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()
}
Run Code Online (Sandbox Code Playgroud)
有没有办法做到这一点?
没有更改方法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.");
}
Run Code Online (Sandbox Code Playgroud)
如果无法更改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.
}
Run Code Online (Sandbox Code Playgroud)
你可以返回一个布尔值来表示返回,如果你可以改变两个()
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;
}
Run Code Online (Sandbox Code Playgroud)
或者你可以内联结构
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.");
}
}
Run Code Online (Sandbox Code Playgroud)