Java: Getting proper context of "this" in anonymous action handler
I noticed a peice of code I was looking at, that the author used:
clas开发者_运维技巧s MainClass
{
protected int someVar = 1;
private SomeClass someClass = new SomeClass(this, new SomeActionListener() {
protected void onAction() {
MainClass.this.someVar ++;
}
});
public MainClass()
{
}
}
Note how he used MainClass.this
to get the proper context of 'this' to change the scope back to MainClass
. I've never seen this done before - can someone explain?
The anonymous instance is bound to the scope of the instance in which it is created. Therefore it can also access everything within. this
would refer to the anonymous instance and MainClass.this
to the instance in which the anonymous instance was created. If for example the someClass
member would have been declared as static
, you could not have used MainClass.this
.
精彩评论