问题
I'd like to know if it's possible (and how if it is) to refer to enclosing anonymous class instance in Java.
Example code:
final Handler handler = new Handler();
handler.post(new Runnable() {
@Override
public void run() {
new Task() {
@Override
public void onTaskFinish() {
handler.post(?); // what should go here?
}
}.execute()
}
});
回答1:
If you were also a JavaScript coder, I bet you wouldn't need to ask this :) There is a trivial way to achieve what you want (and happens to be an important JavaScript idiom due to its peculiar semantics surrounding this
).
handler.post(new Runnable() {
@Override
public void run() {
final Runnable self = this;
new Task() {
@Override
public void onTaskFinish() {
handler.post(self);
}
}.execute()
}
});
来源:https://stackoverflow.com/questions/28784624/how-to-refer-to-enclosing-anonymous-class-instance-in-java