跳出方法从匿名内部类 [英] Break out of a method from anonymous inner class
本文介绍了跳出方法从匿名内部类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个方法:
void someMethod(String someString)
final String[] testAgainst = {...};
....
for(int i = 0; i < testAgainst.length; i++) {
if (someString.equals(testAgainst[i])) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Strings are the same! Overwrite?")
.setTitle("Blah Blah Blah")
.setCancelable(false)
.setPositiveButton("Overwrite", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface di, int which) {
someAction()
}
})
.setNegativeButton("Nah", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface di, int which) {
ESCAPE
}
});
AlertDialog dialog = builder.create();
}
}
doSomeOtherStuff();
}
这里的东西,如果我的code到达 ESCAPE
(即用户决定不覆盖),我要彻底退出方法。我曾尝试...
Here's the thing, if my code reaches ESCAPE
(that is, the user decides not to overwrite), I want to exit the method completely. I have tried...
- 更改
的someMethod()
来返回一个布尔值,然后从负按钮返回,但它不会让我,因为它是一个无效的内部方法中。 - 从
ESCAPE
在外部抓到,但是编译器不会让我抛出一个异常,因为DialogInterface.OnClickListener
不会抛出。 - 使用
破
语句离开为
循环,但这并不能工作。
- changing
someMethod()
to return a boolean, then returning it from the negative button, but it won't let me because it's within a void internal method. - throwing an exception from
ESCAPE
to be caught externally, but the compiler won't let me becauseDialogInterface.OnClickListener
doesn't throw. - using a
break
statement to leave thefor
loop, but that doesn't work either.
这也将是可以接受的只是离开为
循环。我可以解释这一点。我用尽了一切我能找到和我在我束手无策。
It would also be acceptable to simply leave the for
loop. I can account for that. I've tried everything I can find and I'm at my wit's end.
推荐答案
您可以抛出一个RuntimeException或其子类之一。编译器不会抱怨。
You can throw a RuntimeException or one of its subclasses. The compiler won't complain about it.
这篇关于跳出方法从匿名内部类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文