Creating instances of inner classes using reflection in Java can often lead to exceptions similar to the one encountered here. Understanding the nuances of inner class instantiation through reflection is crucial to resolving this issue.
While attempting to instantiate an inner class directly via Class.forName(...) and newInstance(), the underlying InstantiationException occurs because inner classes have an additional "hidden" parameter - the instance of the enclosing class.
To rectify this, employ the following approach:
For instance:
<code class="java">// Exception handling omitted Class<?> enclosingClass = Class.forName("com.mycompany.Mother"); Object enclosingInstance = enclosingClass.newInstance(); Class<?> innerClass = Class.forName("com.mycompany.Mother$Child"); Constructor<?> ctor = innerClass.getDeclaredConstructor(enclosingClass); Object innerInstance = ctor.newInstance(enclosingInstance);</code>
Alternatively, if the inner class does not require access to the enclosing class, consider declaring it as a nested static class instead, as illustrated here:
<code class="java">public class Mother { public static class Child { public void doStuff() { // ... } } }</code>
The above is the detailed content of How to Instantiate Inner Classes with Reflection in Java: Why Do We Need an Enclosing Class Instance?. For more information, please follow other related articles on the PHP Chinese website!