Java Reflections Error: Wrong Number of Arguments

So, I'm trying to call the class 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 a class to it, I get an IllegalArgumentException: the wrong number of arguments. The constructor of the called class, I accept String [] as the only argument. It is also strange that if I change the constructor to an integer and use Integer.TYPE and call c.newInstance (4) or something else, it will work. Can someone explain to me what I'm doing wrong? Thank.

Change ;; Full 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)
+5
source share
2 answers

I'm not sure if this is the best solution, but this should work:

c.newInstance((Object)argArray);
+7

, newInstance(Object...) varargs Object, Object[]. , a String[] Object[], argArray .

jdb solution , . :

c.newInstance(new Object[] {argArray});
+9

All Articles