Java Reflections error: Wrong number of arguments

10,151

Solution 1

I'm not sure if it is the best fix but this should work:

c.newInstance((Object)argArray);

Solution 2

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});
Share:
10,151
de1337ed
Author by

de1337ed

Updated on July 03, 2022

Comments

  • de1337ed
    de1337ed almost 2 years

    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)
    
  • jdb
    jdb over 11 years
    Without the Object[] wrapper newInstance tries to pass multiple String arguments to a single argument constructor. The exception message changes from (java.lang.IllegalArgumentException: argument type mismatch) to (java.lang.IllegalArgumentException: wrong number of arguments) depending on the size of the String array.