148

Given the following code:

public interface Selectable {
  public void select();
}

public class Container implements Selectable {
  public void select() {
  ...
  }
  public void createAnonymousClass() {
    Selectable s = new Selectable() {
      public void select() {
        //see comment below.
      }
    };
  }
}

I want to access Container.select() from within my anonymous class' select() method. However, this.select() would again call the anonymous class' select() method.

My suggestion would be:

Introduce a field into Container, e.g.

private Container self = this;

Now I can access Container.select() by calling self.select() from within the anonymous class.

Is this a reasonable way? Or are there any better ways?

Tom Hawtin - tackline
  • 145,806
  • 30
  • 211
  • 305
Bob
  • 5,510
  • 9
  • 48
  • 80

2 Answers2

282
Container.this.select();
Mykola Golubyev
  • 57,943
  • 15
  • 89
  • 102
43

You can write Container.this.select() to distinct from the inner class !

Eng.Fouad
  • 115,165
  • 71
  • 313
  • 417
PeterMmm
  • 24,152
  • 13
  • 73
  • 111