I am trying to create an instance of a class which has only the following constructor, overwriting the default constructor
public HelloWorld(String[] args)
I am doing the following
Class reflect;
HelloWorld obj = null;
//some logic to generate the class name with full path
reflect = Class.forName(class_name);
Then I am trying to create an object for this class
obj = (HelloWorld)reflect.getConstructor(String[].class)
.newInstance(job1.arg_arr());
arg_arr()
is for converting a list to an array of strings
public String[] arg_arr(){
String arg_list[]=new String[args.size()];
return args.toArray(arg_list);
}
I get the following stack trace when trying to create the instance
java.lang.IllegalArgumentException
:
wrong number of arguments
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:408)
at processmigration.Process_manager.eval(Process_manager.java:175)
at processmigration.Process_manager.run(Process_manager.java:147)
at java.lang.Thread.run(Thread.java:745)
I wonder what is going wrong since I am passing only one argument to newInstance() just like the constructor of the class I am trying to create.
The solution is as follows:
When performing getConstructor(...) and newInstance (...), all your arguments must be inside 1 array. Therefore, I created the arrays params and argsToPass and stored your args in them. Otherwise, it would thing your String[] is a list of arguments and not just 1 argument.
EDIT: Tested code - works!!
newInstance
takes anObject...
argument so when you give it a String[] it passes it as theObject[]
.What you want is the following which tells it you are passing just one argument, not the contents of the array as arguments.