If I have an instance of an inner class, how can I access the outer class from code that is not in the inner class? I know that within the inner class, I can use Outer.this to get the outer class, but I can’t find any external way of getting this.
For example:
public class Outer { public static void foo(Inner inner) { //Question: How could I write the following line without // having to create the getOuter() method? System.out.println('The outer class is: ' + inner.getOuter()); } public class Inner { public Outer getOuter() { return Outer.this; } } }
The bytecode of the
Outer$Innerclass will contain a package-scoped field namedthis$0of typeOuter. That’s how non-static inner classes are implemented in Java, because at bytecode level there is no concept of an inner class.You should be able to read that field using reflection, if you really want to. I have never had any need to do it, so it would be best for you to change the design so that it’s not needed.
Here is how your example code would look like when using reflection. Man, that’s ugly. 😉