当构造函数将字符串数组作为参数时,使用反射创建对象实例
我正在尝试创建一个只有以下构造函数的类的实例,覆盖默认构造函数
I am trying to create an instance of a class which has only the following constructor, overwriting the default constructor
public HelloWorld(String[] args)
我正在做以下事情
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()
用于将列表转换为字符串数组
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);
}
我在尝试创建实例时得到以下堆栈跟踪java.lang.IllegalArgumentException
:
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)
我想知道出了什么问题,因为我只向 newInstance() 传递一个参数,就像我试图创建的类的构造函数一样.
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.
newInstance
接受一个 Object...
参数,所以当你给它一个 String[] 时它会通过它作为 Object[]
.
newInstance
takes an Object...
argument so when you give it a String[] it passes it as the Object[]
.
你想要的是以下内容,它告诉它你只传递一个参数,而不是数组的内容作为参数.
What you want is the following which tells it you are passing just one argument, not the contents of the array as arguments.
.newInstance((Object) job1.arg_arr())