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

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.

Leave a Comment