获取作为文件输入接收的参数类型
问题描述:
我有一个文本文件,作为参数传递给我的程序。该文件包含类名和参数,我应该实例:获取作为文件输入接收的参数类型
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();
答
你需要指定在文本文件中的参数类型,否则它是不可能的Java解决一些在运行参数的不确定性。
例如,如果你有类图书:
public class Book {
public Book() {
}
public Book(Integer id, String name) {
}
public Book(String idx, String name) {
}
}
你提供书:30,饥饿游戏
又会有怎样的代码知道哪个构造函数来接,因为30是一个合法的整数,还合法的字符串?
假设没有你的构造函数是模糊的,这里是如何做到这一点:
String args[] = {"this is id", "this is name"};
Arrays.asList(Book.class.getConstructors()).stream()
.filter(c -> c.getParameterCount() == args.length).forEach(c -> {
if (IntStream.range(0, c.getParameterCount()).allMatch(i -> {
return Arrays.asList(c.getParameterTypes()[i].getDeclaredMethods()).stream()
.filter(m -> m.getName().equals("valueOf")).anyMatch(m -> {
try {
m.invoke(null, args[i]);
return true;
} catch (Exception e) {
return false;
}
});
}))
System.out.println("Matching Constructor: " + c);
});
当我更换args数组,你用构造函数的参数个数进行比较,我得到一个错误 - 局部变量在封闭范围内定义的参数必须是最终的或有效的最终。 – prego
是的,根据Java Spec,lambda要求:“一个lambda表达式只能访问局部变量和封闭块的最终或有效最终参数”。对不起,但我不太清楚你的意思,因为parameterCount()是一个整数,参数是一个字符串数组 –
我的意思是parameters.length – prego