Instantiating Inner Classes with Reflection in Java
Problem:
Attempting to instantiate an inner class using reflection, such as:
<code class="java">Class<?> clazz = Class.forName("com.mycompany.Mother$Child"); Child c = clazz.newInstance();</code>
results in an InstantiationException.
Answer:
When instantiating an inner class, it requires an instance of the enclosing class. To achieve this, use Class.getDeclaredConstructor() to obtain the constructor and provide an instance of the enclosing class as an argument.
Example:
<code class="java">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>
Alternative Solution:
If the inner class does not require access to the enclosing instance, consider using a static nested class instead:
<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 using Reflection in Java?. For more information, please follow other related articles on the PHP Chinese website!