2

I have the following code:

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

I can use member variables of the current Foo instance from inside actionPerformed. I I use this I get the instance of ActionListener. But how can I get a reference to the current Foo instance itself?

gregseth
  • 12,952
  • 15
  • 63
  • 96
  • http://stackoverflow.com/questions/1816458/getting-hold-of-the-outer-class-object-from-the-inner-class-object – Reimeus Nov 30 '15 at 10:26

3 Answers3

3

You can access the Foo instance by using Foo.this:

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

with Classname.this you get the instance in your ActionListener:

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

    public Foo()
    {
        new ActionListener()
        {
            public void actionPerformed( ActionEvent e )
            {
                Foo.this.doSomething();
            }
        }
    };
}
nano_nano
  • 12,351
  • 8
  • 55
  • 83
1

You can create a local variable containing "this" and use it in the Anonymous inner class:

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

        // use thisFoo in here
    }
};
ParkerHalo
  • 4,341
  • 9
  • 29
  • 51