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)
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});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With