2011-12-09 25 views
3

如果我這樣做,「這個」參考在施工期間轉義?

final class FooButton extends JButton{ 
    FooButton(){ 
     super("Foo"); 
     addActionListener(new ActionListener(){ 
      @Override 
      public void actionPerformed(ActionEvent e){ 
       // do stuff 
      } 
     }); 
    } 
} 

我我讓this參考隱含逃脫呢?

+0

你是什麼意思? – adarshr

回答

5

是的,因爲在匿名內部類,你可以這樣訪問:在FooButton對象之前

final class FooButton extends JButton { 
    Foo() { 
     super("Foo"); 
     addActionListener(new ActionListener() { 
      @Override 
      public void actionPerformed(ActionEvent e) { 
       FooButton button = FooButton.this; 
       // ... do something with the button 
      } 
     }); 
    } 
} 

匿名ActionListener的代碼,原則上可以調用,使用FooButton完全初始化。

+0

「FooButton.this」類構造的正式名稱是什麼? – Geek

+1

@Geek,[限定此](http://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.8.4) – mre

1

是的,ActionListener的匿名內部類對this的引用。

1

是的。封閉類的this隱含在非靜態匿名類中。

7

是的,這個引用轉義給了監聽者。由於這個監聽器並不是一個真正的外部類,所以我沒有看到任何問題。

在這裏你可以看到,這個逃逸:

final class FooButton extends JButton{ 
    Foo(){ 
     super("Foo"); 
     addActionListener(new ActionListener(){ 
      private buttonText = FooButton.this.getText(); // empty string 

      @Override 
      public void actionPerformed(ActionEvent e){ 
       // do stuff 
      } 
     }); 
     this.setText("Hello"); 
    } 
}