[英]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. 我得到的类名
className
在运行时,我想这需要一个字符串数组构造函数初始化。 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. 但是我仍然收到一个异常的说法,
wrong number of arguments
,即使我传递的是字符串数组。 I am confused as to how to proceed. 我对如何进行感到困惑。 Any help is appreciated.
任何帮助表示赞赏。
Array types in Java are covariant. Java中的数组类型是协变的。 This means that
Object[] objectArray = stringArray;
这意味着
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. 当你调用
constructor.newInstance
,你的stringArray
被强制转换为Object[]
和你想有两个,分别调用构造函数String
参数。
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: 您要么需要将
stringArray
显式地包装在Object[]
要么将其stringArray
为Object
然后让JVM自动为您包装在Object[]
中:
constructor.newInstance(new Object[] { stringArray });
or 要么
constructor.newInstance((Object) stringArray);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.