从类对象实例化类 [英] instantiate class from class object
问题描述
在Java中,我可以使用类对象动态实例化该类型的类吗?
In java, can I use a class object to dynamically instantiate classes of that type?
即我想要这样的功能.
Object foo(Class type) {
// return new object of type 'type'
}
推荐答案
在Java 9及更高版本中,如果存在声明的零参数(空")构造函数,则应使用在其上的newInstance()
:
In Java 9 and afterward, if there's a declared zero-parameter ("nullary") constructor, you'd use Class.getDeclaredConstructor()
to get it, then call newInstance()
on it:
Object foo(Class type) throws InstantiationException, IllegalAccessException, InvocationTargetException {
return type.getDeclaredConstructor().newInstance();
}
Prior to Java 9, you would have used Class.newInstance
:
Object foo(Class type) throws InstantiationException, IllegalAccessException {
return type.newInstance();
}
...但是从Java 9开始不推荐使用,因为它抛出了构造函数抛出的任何异常,甚至是检查过的异常,但是(当然)没有声明这些检查过的异常,从而有效地绕过了编译时检查过的异常处理. Constructor.newInstance
将来自构造函数的异常包装在InvocationTargetException
中.
...but it was deprecated as of Java 9 because it threw any exception thrown by the constructor, even checked exceptions, but didn't (of course) declare those checked exceptions, effectively bypassing compile-time checked exception handling. Constructor.newInstance
wraps exceptions from the constructor in InvocationTargetException
instead.
以上两种方法都假设有一个零参数构造函数.一种更可靠的方法是通过 Class.getConstructors
,它使您可以使用
Both of the above assume there's a zero-parameter constructor. A more robust route is to go through Class.getDeclaredConstructors
or Class.getConstructors
, which takes you into using the Reflection stuff in the java.lang.reflect
package, to find a constructor with the parameter types matching the arguments you intend to give it.
这篇关于从类对象实例化类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!