在Java中,我可以使用类对象动态实例化该类型的类吗?
即我想要这样的功能。
Object foo(Class type) {
// return new object of type 'type'
}
在Java 9及之后的版本中,如果有一个声明的零参数(“空”)构造函数,则可以使用Class.getDeclaredConstructor()
来获取它,然后在其上调用Class.getDeclaredConstructor()
:
newInstance()
在Java 9之前,您应该使用newInstance()
:
Object foo(Class type) throws InstantiationException, IllegalAccessException, InvocationTargetException {
return type.getDeclaredConstructor().newInstance();
}
...但是从Java 9开始不推荐使用,因为它抛出了构造函数抛出的任何异常,甚至是检查过的异常,但是(当然)没有声明那些检查过的异常,有效地绕过了编译时检查过的异常处理。 Class.newInstance
将构造函数的异常包装在Class.newInstance
中。
以上两者均假设有一个零参数构造函数。一种更可靠的方法是遍历Object foo(Class type) throws InstantiationException, IllegalAccessException {
return type.newInstance();
}
或Constructor.newInstance
,这将带您使用InvocationTargetException
包中的Reflection东西,以找到参数类型与要提供的参数匹配的构造函数。
是的,它称为反射。您可以为此使用Class Class.getDeclaredConstructors
方法。
使用newInstance()方法。