Dynamically create an inner class nested in an abstract class

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?

+4
source share
1 answer

This worked because the constructor simply sets the Outer.this field. He should probably check that its value is not null (so it is not so fast), but faster if it is not.

I would not rely on the fact that it always works, there are all the possibilities that different JVMs, even different updates, will work differently.

as per your previous example, this should work.

 Inner instance = constructor.newInstance(new Outer(){}); 
+5
source

All Articles