How do you get the inclusion class reference from an anonymous inner class in Java?

I am currently creating an explicit reference to this in an outer class, so I have a name for the reference in an anonymous inner class. Is there a better way to do this?

+47
java oop
Aug 27 '08 at 20:36
source share
3 answers

I recently found this. 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 only need an object (instead of calling elements), then Outer.this is the way to go.

+84
Aug 27 2018-08-20
source share

Use EnclosingClass.this

+18
Aug 27 '08 at 20:40
source share

You can use Outer.class to get the class of an external class object (which will return the same class object as Outer.this.getClass (), but more efficient)

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

+1
Sep 16 '08 at 15:18
source share



All Articles