Home  >  Article  >  Java  >  How to Instantiate Inner Classes using Reflection in Java?

How to Instantiate Inner Classes using Reflection in Java?

Patricia Arquette
Patricia ArquetteOriginal
2024-10-28 22:27:30186browse

How to Instantiate Inner Classes using Reflection in Java?

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn