我正在研究这个程序,它以“新id类arg0 arg1 ...”的形式从用户那里获取输入(例如new obj1 String int:5 bool:true ...)。解析此命令后,我需要创建指定类的新实例,并使用“指定的参数”调用其构造函数。现在这是我一直困扰的部分,因为我看到的所有例子都像constructor.newInstance(String.class,bool.class),但在我的情况下,我得到了字符串形式的参数,我是困惑于如何将它们转换为上面的形式并调用该特定的构造函数。参数的数量也不清楚,那么我的问题是否有任何简单的解决方案? (制作给定类的实例并使用指定数量的参数调用构造函数) 示例命令和我需要执行的操作是:
new x java.util.ArrayList int:5 --> x refers to “new ArrayList(5)”
答案 0 :(得分:2)
成功解析字符串后,可以使用Class.getConstructor()
或Class.getDeclaredConstructor()
来获取所需的构造函数。这两种方法的主要区别在于Class.getDeclaredConstructor()
还允许您调用私有构造函数(在源代码中声明的任何内容,因此名称)。以下是您的测试用例的示例:
int argListLength = 1; // This should really be the number of parsed arguments
Class[] argumentTypes = new Class[argListLength];
Object[] argumentValues = new Object[argListLength];
// In reality you will want to do the following statement in a loop
// based on the parsed types
argumentTypes[0] = Integer.TYPE;
// In reality you will want to do the following statement in a loop
// based on the parsed values
argumentValues[0] = 5;
Constructor<ArrayList> constructor = null;
try {
consrtuctor = java.util.ArrayList.class.getConstructor(argumentTypes);
} catch(NoSuchMethodException ex) {
System.err.println("Unable to find selected constructor..."); // Display an error
// return or continue would be nice here
}
ArrayList x = null;
try {
x = constructor.newInstance(argumentValues);
} catch(InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException ex) {
System.err.println("Unable to call selected constructor..."); // Display an error
// return or continue would be nice here
}
您可能会注意到在调用构造函数时可能会出现很多问题。唯一特殊的是InvocationTargetException
,它包装了一个成功调用的构造函数抛出的异常。