[英]Get arguments types from Constructor object (Java Reflection)
I try to create an object out of class class (via java reflection) - user choose a constructor and I need to read variables for this constructor (it supposed to be some of the primitive types).我尝试从类类中创建一个对象(通过 java 反射) - 用户选择一个构造函数,我需要读取这个构造函数的变量(它应该是一些原始类型)。
As you can see now my code works only for integer params.正如您现在看到的,我的代码仅适用于整数参数。
How can I dynamically figure out type of the current argument and read it from the keyboard?如何动态找出当前参数的类型并从键盘读取它?
public static Object chooseConstr(Class cls) throws IllegalAccessException, InstantiationException, InvocationTargetException {
Scanner keyboard = new Scanner(System.in);
Constructor[] constructors = cls.getDeclaredConstructors();
System.out.println("Choose constructor from the list: ");
System.out.println(Arrays.toString(constructors));
int constr = keyboard.nextInt();
constr--;
Object[] arguments=new Object[constructors[constr].getParameterCount()];
for(int i=0; i<arguments.length; i++){
System.out.println("Write argument #"+(i+1));
arguments[i]=keyboard.nextInt();
}
Object object = constructors[constr].newInstance(arguments);
System.out.println("Object created!");
return object;
}
This will be tricky.这将是棘手的。 Of course scanner has some basic methods to read in some types, but if you want to read other kinds of arguments you'll have to figure out a way to read them yourself.当然,scanner 有一些基本方法可以读取某些类型,但是如果您想读取其他类型的参数,则必须自己想办法读取它们。
For this, you can use Constructor.getParameterTypes()
:为此,您可以使用Constructor.getParameterTypes()
:
...
Object[] arguments = new Object[constructors[constr].getParameterCount()];
Class<?>[] pTypes = constructors[constr].getParameterTypes();
for (int i = 0; i < arguments.length; i++) {
System.out.println("Write argument #" + (i + 1) + ". Of type: "+pTypes[i].getName());
if(pTypes[i].equals(int.class)) {
arguments[i] = keyboard.nextInt(); // read an int
} else if(pTypes[i].equals(String.class)) {
arguments[i] = keyboard.next(); // read a String
} else {
// custom read code for other types
}
}
...
Note that the above is not complete, scanner has more methods to read other types too, which I didn't show here.请注意,以上并不完整,scanner 也有更多方法可以读取其他类型,这里我没有展示。
The best strategy for reading other types of arguments, is probably to read them as a string and convert them to the corresponding objects through some factory method.读取其他类型参数的最佳策略,可能是将它们作为字符串读取,并通过某种工厂方法将它们转换为相应的对象。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.