samedi 24 juillet 2021

Why do I get Java.lang.IllegalArgumentException: wrong number of arguments while creating new instance with private constructor using reflection

java.lang.IllegalArgumentException: wrong number of arguments
at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:64)
at java.base/jdk.internal.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.base/java.lang.reflect.Constructor.newInstanceWithCaller(Constructor.java:500)
at java.base/java.lang.reflect.Constructor.newInstance(Constructor.java:481)
at beans.ClientTest.main(ClientTest.java:14)

i am trying to invoke private constructor with newInstance() method using reflection. Here is the code.


public class Test {
    private String name;
    private int id;
    
    private Test() {
        System.out.println("private constructor.. Test");
    }

    public Test(int id) {
        super();
        this.id = id;
    }

    public Test(String name, int id) {
        super();
        this.name = name;
        this.id = id;
    }

    public Test(String name) {
        super();
        this.name = name;
    }
}

import java.lang.reflect.Constructor;

public class ClientTest {

    @SuppressWarnings({ "rawtypes", "unchecked" })
    public static void main(String[] args) {
        
        try {
            Class cl = Class.forName("beans.Test");
            Constructor[] c =  cl.getDeclaredConstructors();
            c[0].setAccessible(true);
            c[0].newInstance();
            
            for(Constructor cnt : c) {
                System.out.println(cnt);
            }
        }catch(Exception e) {
            e.printStackTrace();
        }
    }
}




Aucun commentaire:

Enregistrer un commentaire