Java Minutiae - Instantiating inner classes
Pop quiz - without reflection, access to private members, or changing the source, create an instance ofInner
.public final class Outer {
public static final Outer INSTANCE = new Outer();
private Outer() { }
public class Inner { }
}
Note that Inner is non-static, so each
Inner
has a reference to its containing Outer
.Show Answer
Well it turns out that you can 'dereference' a containing instance to instantiate an inner class. The syntax is awkward, but it works:
Inner inner = Outer.INSTANCE.new Inner();
I've found this syntax most useful for testing package-scoped inner classes.