Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Reflections error: Wrong number of arguments

So I'm trying to invoke a classes constructor at runtime. I have the following code snippet:

String[] argArray = {...};
...
Class<?> tempClass = Class.forName(...);
Constructor c = tempClass.getConstructor(String[].class); 
c.newInstance(argArray);
...

Whenever I compile the code and pass it a class, I get an IllegalArgumentException: wrong number of arguments. The constructor of the class I'm calling takes in a String[] as the only argument. What's also weird is that if I change the constructor to take in an integer and use Integer.TYPE and call c.newInstance(4) or something, it works. Can someone explain to me what I'm doing wrong? Thank you.

Edit;; Complete error:

java.lang.IllegalArgumentException: wrong number of arguments
[Ljava.lang.String;@2be3d80c
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
at java.lang.reflect.Constructor.newInstance(Unknown Source)
like image 938
de1337ed Avatar asked Jan 24 '13 00:01

de1337ed


1 Answers

This is happening because newInstance(Object...) takes varargs of Object, in other words Object[]. Since arrays are covariant, a String[] is also an Object[], and argArray is being interpretted as all arguments instead of first argument.

jdb's solution works because it prevents the compiler from misunderstanding. You could also write:

c.newInstance(new Object[] {argArray});
like image 53
Paul Bellora Avatar answered Nov 15 '22 10:11

Paul Bellora