I understand that creating an instance of an inner class (i.e. non-static) requires an instance of the incoming class. This makes things a little more complicated if the enclosing class is abstract (don't ask). Consider the following.
abstract class Outer { class Inner {} }
Creating an Inner instance can still be done statically, for example with an anonymous class.
Inner instance = new Outer() {}.new Inner();
But how do you dynamically accomplish the same thing with Constructor.newInstance ? (Note that I said dynamically, suppose you don't know the name of the outer class.) You need to pass an instance of the surrounding class for the first argument, according to JLS 15.9.3 , and if there is a way to create something "on the fly" so that satisfy the abstract parameter, I do not know about it (bonus points for any ideas there).
In short, I accidentally hit null like this.
Constructor<Inner> constructor = Inner.class.getDeclaredConstructor(Outer.class); Object argument = null; Inner instance = constructor.newInstance(argument);
Imagine my surprise when this worked. My question is: why does this work? And will it always work?
source share