Call constructor of nested class

suggest change

If you want to create an instance of an inner nested class you need to provide a class object of the enclosing class as an extra parameter with Class#getDeclaredConstructor.

public class Enclosing{
    public class Nested{
    public Nested(String a){
            System.out.println("Constructor :String => "+a);
    public static void main(String args[]) throws Exception {
        Class<?> clazzEnclosing = Class.forName("Enclosing");            
        Class<?> clazzNested = Class.forName("Enclosing$Nested");
        Enclosing objEnclosing = (Enclosing)clazzEnclosing.newInstance();
        Constructor<?> constructor = clazzNested.getDeclaredConstructor(new Class[]{Enclosing.class, String.class});
        Nested objInner = (Nested)constructor.newInstance(new Object[]{objEnclosing, "StackOverFlow"});

If the nested class is static you will not need this enclosing instance.

Feedback about page:

Optional: your email if you want me to get back to you:

Table Of Contents