2015-11-30 119 views
2

獲取refecence噸contining比如我有以下代碼:從匿名類

class Foo 
{ 
    public Foo() 
    { 
     new ActionListener() 
     { 
      public void actionPerformed(ActionEvent e) 
      { 
       // how can I use a reference to Foo here 
      } 
     } 
    } 
} 

我可以使用當前Foo實例的成員變量從內actionPerformed。我使用this我得到ActionListener的實例。但是我怎樣才能得到當前Foo實例本身的參考?

+0

http:// st ackoverflow.com/questions/1816458/getting-hold-of-the-outer-class-object-from-the-inner-class-object – Reimeus

回答

3

您可以通過使用Foo.this訪問富實例:

class Foo 
{ 
    public Foo() 
    { 
    new ActionListener() 
    { 
     @Override 
     public void actionPerformed(final ActionEvent e) 
     { 
     Foo thisFoo = Foo.this; 
     } 
    }; 
    } 
} 
3

Classname.this你得到的實例在ActionListener

class Foo 
{ 
    void doSomething(){ 
     System.out.println("do something"); 
    }; 

    public Foo() 
    { 
     new ActionListener() 
     { 
      public void actionPerformed(ActionEvent e) 
      { 
       Foo.this.doSomething(); 
      } 
     } 
    }; 
} 
1

您可以創建一個包含「此」,並使用一個局部變量它在匿名內部類:

final Foo thisFoo = this; 
ActionListener al = new ActionListener() { 
    @Override 
    public void actionPerformed(ActionEvent arg0) { 

     // use thisFoo in here 
    } 
};