6

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)
1
  • Could you post the complete error? Commented Jan 24, 2013 at 0:08

2 Answers 2

12

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});
Sign up to request clarification or add additional context in comments.

Comments

10

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

c.newInstance((Object)argArray);

1 Comment

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.