Java 从匿名类获取refecence ton contining实例

Java 从匿名类获取refecence ton contining实例,java,anonymous-class,Java,Anonymous Class,我有以下代码: class Foo { public Foo() { new ActionListener() { public void actionPerformed( ActionEvent e ) { // how can I use a reference to Foo here } } } } 我可以从ac

我有以下代码:

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

我可以从
actionPerformed
内部使用当前
Foo
实例的成员变量。我使用
this
获取
ActionListener
的实例。但是如何获取对当前
Foo
实例本身的引用呢?

您可以使用
Foo来访问Foo实例。此

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

使用
Classname。此
可在
ActionListener
中获取实例:

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

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

您可以创建包含“this”的局部变量,并在匿名内部类中使用它:

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

        // use thisFoo in here
    }
};