使用反射[Java]在运行时使用指定参数调用构造函数

使用反射[Java]在运行时使用指定参数调用构造函数,java,reflection,Java,Reflection,我正在开发这个程序,它以“新id类arg0 arg1…”的形式接收用户的输入(例如,新obj1字符串int:5 bool:true…)。解析此命令后,我需要创建指定类的新实例,并使用“指定参数”调用其构造函数。现在这是我一直坚持的部分,因为我看到的所有示例都像constructor.newInstance(String.class,bool.class),但在我的例子中,我得到的参数是字符串形式的,我不知道如何将它们转换为上述形式并调用特定的构造函数。争论的数量也不清楚,所以我的问题有没有简单的

我正在开发这个程序,它以“新id类arg0 arg1…”的形式接收用户的输入(例如,新obj1字符串int:5 bool:true…)。解析此命令后,我需要创建指定类的新实例,并使用“指定参数”调用其构造函数。现在这是我一直坚持的部分,因为我看到的所有示例都像constructor.newInstance(String.class,bool.class),但在我的例子中,我得到的参数是字符串形式的,我不知道如何将它们转换为上述形式并调用特定的构造函数。争论的数量也不清楚,所以我的问题有没有简单的解决办法?(生成给定类的实例并使用指定数量的参数调用构造函数) 我需要执行的示例命令和操作如下:

new x java.util.ArrayList int:5 --> x refers to “new ArrayList(5)”

成功解析字符串后,可以使用
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
}
int argListLength=1;//这应该是解析参数的数量
Class[]argumentTypes=新类[argListLength];
Object[]argumentValues=新对象[argListLength];
//实际上,您需要在循环中执行以下语句
//基于解析的类型
argumentTypes[0]=Integer.TYPE;
//实际上,您需要在循环中执行以下语句
//基于解析的值
参数值[0]=5;
构造函数=null;
试一试{
constructor=java.util.ArrayList.class.getConstructor(argumentTypes);
}catch(NoSuchMethodException-ex){
System.err.println(“无法找到所选构造函数…”);//显示错误
//返回或继续在这里将是很好的
}
ArrayList x=null;
试一试{
x=构造函数.newInstance(参数值);
}catch(实例化异常| IllegalAccessException | IllegalArgumentException | InvocationTargetException ex){
System.err.println(“无法调用所选构造函数…”);//显示错误
//返回或继续在这里将是很好的
}

您可能会注意到,调用构造函数时可能会出现很多问题。唯一特殊的是
InvocationTargetException
,它封装了成功调用的构造函数抛出的异常。

您必须更具体一些。给我们一个你的输入和你期望它做什么的例子。首先阅读
Class
Constructor
的javadoc。你成功地解析了整个过程吗?是的,我已经解析到我检查参数数量是否为0的程度,然后使用Class c=Class.forName(“此处的类名”)创建新对象;Object obj=c.newInstance();