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

How to Instantiate Inner Classes using Reflection in Java?

Patricia Arquette
Release: 2024-10-28 22:27:30
Original
294 people have browsed it

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>
Copy after login

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>
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template