Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IllegalArgumentException: wrong number of arguments in Java Constructor.newInstance()

Consider the following code,

public class StartUp {

    public StartUp(String[] test){}

    public static void main(String[] args) throws Exception{
        Constructor cd = StartUp.class.getConstructor(String[].class);
        System.out.println(cd.newInstance(new String[]{}).toString());
    }
}

What's wrong with it? I get the following Exception:

Exception in thread "main" java.lang.IllegalArgumentException: wrong number of arguments at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:39) at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:27) at java.lang.reflect.Constructor.newInstance(Constructor.java:513) at com.test.StartUp.main(StartUp.java:10)

like image 620
xandy Avatar asked Feb 28 '11 13:02

xandy


1 Answers

Your String[] is being implicitly converted to Object[] and taken as an empty array of arguments, instead of as a single argument which is an empty array. Try this:

Object arg = new String[0];
System.out.println(cd.newInstance(arg).toString());

or

System.out.println(cd.newInstance(((Object)new String[0]).toString());

or even avoid the compiler having to create the array for you at all:

System.out.println(cd.newInstance(new Object[] { new String[0] }).toString());

Basically this is a mixture of varargs handling and array covariance :(

like image 82
Jon Skeet Avatar answered Nov 15 '22 01:11

Jon Skeet