[英]How to break/exit different levels of method-calling in Java
比方說我有:
public void one() {
two();
// continue here
}
public void two() {
three();
}
public void three() {
// exits two() and three() and continues back in one()
}
有什么方法可以做到這一點?
沒有更改方法two()的唯一方法是引發Exception。
如果可以更改代碼,則可以返回一個布爾值,告訴調用者返回。
但是,最簡單的解決方案是將這些方法內聯為一個更大的方法。 如果太大,則應以其他方式重新構造它,而不要在這樣的方法之間放置復雜的控件。
說你有
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;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.