0
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();
        }
    }
}
1
  • 5
    What makes you think the constructor at index 0 is the the private no-args constructor? Commented Jul 24, 2021 at 9:28

1 Answer 1

4

Please refer to the docs for getDeclaredConstructors().

Here it says (emphasis mine)

The elements in the array returned are not sorted and are not in any particular order

It is safer to use the method for getting a specific constructor getDeclaredConstructor(Class<?>... parameterTypes). That way you can specify exactly which constructor you want.

Since this method takes a vararg as argument, to get the no-arg constructor you can simply call cl.getDeclaredConstructor().

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.