"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Instantiate Nested Classes in Java Using Reflection?

How to Instantiate Nested Classes in Java Using Reflection?

Published on 2024-11-15
Browse:302

How to Instantiate Nested Classes in Java Using Reflection?

Instantiation of Nested Classes in Java via Reflection

The inability to instantiate the inner class defined in the provided Java code using standard reflection methods is a common pitfall faced by Java developers. When attempting to create an instance directly using Class.newInstance(), the issue arises due to the presence of a hidden parameter representing an instance of the enclosing class.

To successfully instantiate an inner class, it's necessary to employ Class.getDeclaredConstructor() to access the constructor and provide an instance of the enclosing class as an argument. The following code snippet illustrates this approach:

// Exceptions omitted for brevity
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);

Alternatively, if the nested class is not dependent on the enclosing instance, a more straightforward solution is to declare it as a static nested class:

public class Mother {
    public static class Child {
        public void doStuff() {
            // ...
        }
    }
}

By utilizing these approaches, developers can effectively instantiate both dependent and independent inner classes using reflection in Java.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3