0
我有一个文本文件,作为参数传递给我的程序。该文件包含类名和参数,我应该实例:获取作为文件输入接收的参数类型
Home:
SmartMeter:30,false
我想创建实例,使用反射,但我无法弄清楚如何获得的实际类型的,我从文件中获取的参数。我得到这个之后,我想将它们与这个类的所有构造函数的参数类型进行比较,并选择正确的。这是迄今为止我所编写的代码:
Scanner scan = new Scanner(new File(args[0]));
String[] classNameAndParameters;
String[] parameters;
while (scan.hasNextLine()) {
classNameAndParameters = scan.nextLine().split(":");
Class<?> c = Class.forName(classNameAndParameters[0]);
// i check for the length too because it throws arrayoutofbounds exception
if (classNameAndParameters.length > 1 && classNameAndParameters[1] != null) {
parameters = classNameAndParameters[1].split(",");
// get all constructors for the created class
Constructor<?>[] constructors = c.getDeclaredConstructors();
for(int i = 0; i < constructors.length; i++) {
Constructor<?> ct = constructors[i];
Class<?> pvec[] = ct.getParameterTypes();
for (int j = 0; j < pvec.length; j++) {
System.out.println("param #" + j + " " + pvec[j]);
}
}
//i should match the parameter types of the file with the parameters of the available constructors
//Object object = consa.newInstance();
} else {
// default case when the constructor takes no arguments
Constructor<?> consa = c.getConstructor();
Object object = consa.newInstance();
}
}
scan.close();
当我更换args数组,你用构造函数的参数个数进行比较,我得到一个错误 - 局部变量在封闭范围内定义的参数必须是最终的或有效的最终。 – prego
是的,根据Java Spec,lambda要求:“一个lambda表达式只能访问局部变量和封闭块的最终或有效最终参数”。对不起,但我不太清楚你的意思,因为parameterCount()是一个整数,参数是一个字符串数组 –
我的意思是parameters.length – prego