[英]creating instance of object using reflection , when the constructor takes an array of strings as argument
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 arg_arr()
用于将列表转换为字符串数组
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
: 尝试创建实例
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. 我想知道怎么回事,因为我只将一个参数传递给newInstance(),就像我要创建的类的构造函数一样。
newInstance
takes an Object...
argument so when you give it a String[] it passes it as the Object[]
. newInstance
带有一个Object...
参数,因此当您给它一个String []时,它将作为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())
The solution is as follows: 解决方法如下:
When performing getConstructor(...) and newInstance (...), all your arguments must be inside 1 array. 当执行getConstructor(...)和newInstance(...)时,所有参数必须在1个数组内。 Therefore, I created the arrays params and argsToPass and stored your args in them.
因此,我创建了数组params和argsToPass并将您的args存储在其中。 Otherwise, it would thing your String[] is a list of arguments and not just 1 argument.
否则,您的String []会是参数列表,而不仅仅是1个参数。
Class reflect;
HelloWorld obj = null;
//some logic to generate the class name with full path
reflect = HelloWorld.class;
Class[] params = new Class[1];
params[0] = String[].class;
Object[] argsToPass = new Object[1];
argsToPass[0] = job1.arg_arr();
obj = (HelloWorld)reflect.getConstructor(params).newInstance(argsToPass);
EDIT: Tested code - works!! 编辑:经过测试的代码-工作!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.