creating instance of object using reflection , whe

2019-07-16 09:47发布

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.

2条回答
劫难
2楼-- · 2019-07-16 10:27

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.

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!!

查看更多
贪生不怕死
3楼-- · 2019-07-16 10:40

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())
查看更多
登录 后发表回答