Accessing 'this' in anonymous methods
I'm trying to do a simple global exception handler in my Android app and I am having troubles:
public class TicTacToe extends Activity {
/** Call开发者_如何转开发ed when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Thread.currentThread().setUncaughtExceptionHandler(new UncaughtExceptionHandler() {
@Override
public void uncaughtException(Thread thread, Throwable ex) {
Toast.makeText(this, "TOAST", Toast.LENGTH_LONG);
}
});
setContentView(R.layout.main);
}
}
I'm a rather new with both Android AND java but in .NET that would work. Can't I access local variable from anonymous methods in java? If so, how should I rewrite it?
Thanks, Vitaly
You can but not in that way. this
is referred to the UncaughtExceptionHandler
object.
Change this
to TicTacToe.this
Also you should have a compile time error. It isn't?
As mentioned in another answer, the trick is this
is shadowed. Another way to get around that is to add a method in the outer class that returns this
.
It realize this junks up the class signature a little bit, but if you keep the method private, that doesn't seem like a big deal. Does anybody have comments on how this is better or worse than other solutions?
public MyOuterClass {
private MyOuterClass getThis() {
return this;
}
private void outerClassMethod(new MyAnonymousClass() {
public void anonymousClassMethod() {
doSomething(getThis());
}
});
}
精彩评论