开发者

Java: Getting proper context of "this" in anonymous action handler

开发者 https://www.devze.com 2023-03-02 19:24 出处:网络
I noticed a peice of code I was looking at, that the author used: clas开发者_运维技巧s MainClass

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消