Java:使用参数从类名动态创建对象

Java:使用参数从类名动态创建对象,java,reflection,Java,Reflection,我有一个Java类,它的名称存储在数据库中,我想在运行时加载它。我正在使用反射来尝试这样做,但当前代码抛出InvocationTargetException: String classname = "my.test.path.Class"; String details = "Some text"; Integer id = 123; Class<?> cls = Class.forName(classname); Constructor<?> cons = cls.g

我有一个Java类,它的名称存储在数据库中,我想在运行时加载它。我正在使用反射来尝试这样做,但当前代码抛出InvocationTargetException:

String classname = "my.test.path.Class";
String details = "Some text";
Integer id = 123;

Class<?> cls = Class.forName(classname);
Constructor<?> cons = cls.getConstructors();
for (Constructor<?> con : cons) {
    System.out.println(con.toString()); // Does find the constructor
}
Constructor<?> constructor = cls.getConstructor(Integer.class, String.class);
ClassInterface object = (ClassInterface) constructor.newInstance(id, details);
例外情况如下:

java.lang.reflect.InvocationTargetException
  at test.path.Main...
这是上面代码所在的类,而不是调用的构造函数。
InvocationTargetException
中的在构造函数执行期间发生异常时引发:

InvocationTargetException-如果基础构造函数引发异常


检查参数(id和详细信息)是否对构造函数有效,以及它们是否可以生成异常。

请发布
System.out.println(con.toString())的输出
id、details
的定义以及异常stacktrace
[帮助我]
InvocationTargetException
通常意味着代码内部出错,您正在使用反射调用的代码。在本例中,是实际的构造函数。请密切注意异常转储中的“起因”部分。这对我来说很有效,你应该发布类的构造函数定义,并根据请求进行更新。如果你是对的,异常指向我试图创建类的行,但导致问题的是构造函数本身引发的异常。谢谢
java.lang.reflect.InvocationTargetException
  at test.path.Main...