Is it possible to create an instance of inner class using Java Reflection?

You need to jump through a few hoops to do this. First, you need to use Class.getConstructor() to find the Constructor object you want to invoke:

Returns a Constructor object that
reflects the specified public
constructor of the class represented
by this Class object. The
parameterTypes parameter is an array
of Class objects that identify the
constructor’s formal parameter types,
in declared order. If this Class
object represents an inner class
declared in a non-static context, the
formal parameter types include the
explicit enclosing instance as the
first parameter.

And then you use Constructor.newInstance():

If the constructor’s declaring class
is an inner class in a non-static
context, the first argument to the
constructor needs to be the enclosing
instance

Leave a Comment