Home  >  Article  >  Java  >  How to Instantiate Inner Classes with Reflection in Java: Why Do We Need an Enclosing Class Instance?

How to Instantiate Inner Classes with Reflection in Java: Why Do We Need an Enclosing Class Instance?

DDD
DDDOriginal
2024-10-29 08:09:30958browse

How to Instantiate Inner Classes with Reflection in Java: Why Do We Need an Enclosing Class Instance?

Instantiating Inner Classes with Reflection in Java

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:

  1. Obtain the enclosing class using Class.forName(...).
  2. Create an instance of the enclosing class using newInstance().
  3. Retrieve the inner class using Class.forName(...).
  4. Utilize getDeclaredConstructor(...) to access the inner class constructor, specifying the enclosing class as an argument.
  5. Finally, instantiate the inner class using the retrieved constructor and supply the enclosing class instance as the first parameter.

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!

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