How do you get a reference to the enclosing class from an anonymous inner class in Java?

JavaOop

Java Problem Overview


I'm currently creating an explicit reference to this in the outer class so that I have a name to refer to in the anonymous inner class. Is there a better way to do this?

Java Solutions


Solution 1 - Java

I just found this recently. Use OuterClassName.this.

class Outer {
    void foo() {
        new Thread() {
            public void run() {
                Outer.this.bar();
            }
        }.start();
    }
    void bar() {
        System.out.println("BAR!");
    }
}

Updated If you just want the object itself (instead of invoking members), then Outer.this is the way to go.

Solution 2 - Java

Use EnclosingClass.this

Solution 3 - Java

You can still use Outer.class to get the class of the outer class object (which will return the same Class object as Outer.this.getClass() but is more efficient)

If you want to access statics in the enclosing class, you can use Outer.name where name is the static field or method.

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
QuestionBill the LizardView Question on Stackoverflow
Solution 1 - JavaFrank KruegerView Answer on Stackoverflow
Solution 2 - JavaJohn TopleyView Answer on Stackoverflow
Solution 3 - JavaScott StanchfieldView Answer on Stackoverflow