在java中,我可以使用类对象来动态实例化该类型的类吗?
即我想要这样的功能。
Object foo(Class type) {
// return new object of type 'type'
}
最佳答案
在 Java 9 及之后的版本中,如果有声明的零参数(“nullary”)构造函数,您将使用 Class.getDeclaredConstructor()
得到它,然后打电话newInstance()
在上面:
Object foo(Class type) throws InstantiationException, IllegalAccessException, InvocationTargetException {
return type.getDeclaredConstructor().newInstance();
}
在 Java 9 之前,您会使用 Class.newInstance
:
Object foo(Class type) throws InstantiationException, IllegalAccessException {
return type.newInstance();
}
...但它从 Java 9 开始被弃用,因为它抛出构造函数抛出的任何异常,甚至是已检查的异常,但没有(当然)声明那些已检查的异常,有效地绕过了编译时已检查的异常处理。 Constructor.newInstance
将来自构造函数的异常包装在 InvocationTargetException
中。
以上两个都假设有一个零参数构造函数。一条更稳健的路线是通过 Class.getDeclaredConstructors
或 Class.getConstructors
,这将带您使用 java.lang.reflect
中的 Reflection 内容包,以找到参数类型与您打算为其提供的参数相匹配的构造函数。
关于java - 从类对象实例化类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3036777/