私が持っているとしましょう:
public void one() {
two();
// continue here
}
public void two() {
three();
}
public void three() {
// exits two() and three() and continues back in one()
}
これを行う方法はありますか?
私が持っているとしましょう:
public void one() {
two();
// continue here
}
public void two() {
three();
}
public void three() {
// exits two() and three() and continues back in one()
}
これを行う方法はありますか?
メソッドtwo()を変更せずにこれを行う唯一の方法は、例外をスローすることです。
コードを変更できる場合は、呼び出し元に戻るように指示するブール値を返すことができます。
ただし、最も簡単な解決策は、メソッドを1つの大きなメソッドにインライン化することです。これが大きすぎる場合は、別の方法で再構築し、このようなメソッド間に複雑なコントロールを配置しないでください。
あなたが持っていると言う
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()を変更できる場合は、ブール値を返してreturnと言うことができます。
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.");
}
}
メソッドを変更できると仮定すると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;
}
コードを見ると、1つを呼び出すと、2つを呼び出し、3つを呼び出します。そのままにしておくと、まさにそれが実行されます。2つ後の行(1つ)は、2つから戻ったときにのみ実行され、2つが3つで終了するまで実行されません。