从匿名 class 获取对包含实例的引用

Get refecence ton contining instance from anonymous class

我有以下代码:

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.this:

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

使用 Classname.this 您将在 ActionListener:

中获得实例
class Foo 
{
  void doSomething(){
      System.out.println("do something");
  };

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

您可以创建一个包含 "this" 的局部变量并在匿名内部使用它 class:

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

        // use thisFoo in here
    }
};