Access "this" from Java anonymous class

JavaThisAnonymous Class

Java Problem Overview


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.
}
};
}
}

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?

Java Solutions


Solution 1 - Java

Container.this.select();

Solution 2 - Java

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionBobView Question on Stackoverflow
Solution 1 - JavaMykola GolubyevView Answer on Stackoverflow
Solution 2 - JavaPeterMmmView Answer on Stackoverflow