因此,我正在从文件中读取数据,并且根据读取的文本,程序将使用与行上的参数匹配的类的构造函数。因此,文本行给出的参数被存储到一个ArrayList中:
List<Object> parameters = new ArrayList<Object>();
然后我应该能够从这些参数创建一个对象,如下所示:
constructor.newInstance(objects);
但我不太确定如何才能实现这一目标?
try {
Class<?> objectClass = Class.forName("com.editor.object." +line.substring(4, from+4));
Constructor[] allConstructors = objectClass.getDeclaredConstructors();
for(Constructor constructor : allConstructors){
Class<?>[] parameters = constructor.getParameterTypes();
if(objects.size() == parameters.length){
for(int i = 0; i < parameters.length; i++){
if(objects.get(i).getClass().equals(parameters[i])){
if(i + 1 == parameters.length){
return constructor.newInstance(objects); //<-- This doesen't work, I have no idea how should I call the "random" constructor?
}
}
}
}
}
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InstantiationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
编辑 1: 一个例子: 我有以下行
新平台(1, 1, 1, 1, 1);
-> 将使用给定的参数创建一个新的 Platform 对象。引用的类和构造函数可能几乎是任何东西,所以我不能依赖这样的东西。当然,我可以在代码中运行它,但我想了解更多信息,这就是为什么我不会用最简单的方法来实现。
最佳答案
Constructor.newInstance
是一个可变参数方法:其类型签名为 Constructor.newInstance(Object... args)
。如果您使用 ArrayList 作为单个参数来调用它,则将被解释为:
Constructor.newInstance(new Object[] { objects })
因为ArrayList
不是数组类型。除非该构造函数恰好接受单个 List
参数,否则这将会失败,即使如此,它也可能会失败,因为列表中的元素不是该构造函数所需的类型。
相反,您可以将其调用为:
Constructor.newInstance(objects.toArray())
从调用构造函数的角度来看,它将列表“分解”为单独的对象。
关于Java,使用参数列表进行构造函数调用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31711933/