简体   繁体   中英

Java Instantiate a class at run time with String[] stringArray parameters

I am having trouble in getting the concrete implementation of the class at the runtime. I get the name of class className at run time and I want to initialize it with the constructor which takes in a String array. I have the following

stringArray = new String[]{"abc", "def"};
Class clazz = Class.forName(className);
Constructor<MyCustomInterface> constructor = null;
MyCustomInterface myCustomObject = null;
constructor = clazz.getDeclaredConstructor(String[].class);  // Gives constructor which takes in String[] I assume
myCustomObject =  constructor.newInstance(stringArray);   // I am providing the same here

In my Implementation Of Custom Interface I have

public class MyClass implements MyCustomInterface{
    public MyClass(String args[]) throws Exception{
        //My custom constructor
    }
}

But I still get an exception saying, wrong number of arguments , even though I am passing a string array. I am confused as to how to proceed. Any help is appreciated.

Array types in Java are covariant. This means that Object[] objectArray = stringArray; is a perfectly valid statement.

When you call constructor.newInstance , your stringArray is being casted to Object[] , and you are trying to invoke the constructor with two, separate String arguments.

You either need to explicitly wrap your stringArray in an Object[] or cast it to Object and let the JVM automagically wrap it in an Object[] for you:

constructor.newInstance(new Object[] { stringArray });

or

constructor.newInstance((Object) stringArray);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM