我有一个文本文件,作为参数传递给我的程序。该文件包含类名和参数,我应该实例化它们:
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();发布于 2017-07-19 04:43:26
您需要在文本文件中指定参数类型,否则Java不可能解决运行时中某些参数的模糊性。
例如,如果您有类Book:
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);
});https://stackoverflow.com/questions/45174988
复制相似问题