This, in fact, is a very good question if, for example, you need to be able to check if two distinct instances of an Innner
class share the same instance of Outer
class (== or equals depending on the context).
I'd suggest to make a general purpose interface (not absolutely required for named inner classes but can be "instancedof"/casted to):
public interface InnerClass<Outer> {
Outer getOuter();
}
that can be applied to any named inner class.
Then you do something like:
class MyInnerClass implements InnerClass<Outer> {
Outer getOuter() {
return Outer.this;
}
// remaining implementation details
}
and this way you can access outer class from any inner class implementing InnerClass<Outer>
interface (and check it actually implements it).
If your inner class is anonymous, you can only do (thanks to Rich MacDonald for its sample):
new InterfaceOrAbstractClass<Outer>() {
Outer getOuter() { // super inefficient but this is the only way !
return (Outer)getClass().getDeclaredField("this$0");
}
/* other methods */
}
but InterfaceOrAbstractClass
must implements InnerClass<Outer>
to be able to access getOuter()
outside of the anonymous class body!
It would be so much easier if javac automatically implemented some kind of InnerClass<Outer>
interface on ALL inner classes, and it could do that super efficiently even on anonymous classes (no sluggish introspection processing)!