[英]instantiate class from class object
In java, can I use a class object to dynamically instantiate classes of that type?在java中,我可以使用类对象动态实例化该类型的类吗?
ie I want some function like this.即我想要一些这样的功能。
Object foo(Class type) {
// return new object of type 'type'
}
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:在 Java 9 及更高版本中,如果有一个声明的零参数(“空”)构造函数,您将使用
Class.getDeclaredConstructor()
来获取它,然后对其调用newInstance()
:
Object foo(Class type) throws InstantiationException, IllegalAccessException, InvocationTargetException {
return type.getDeclaredConstructor().newInstance();
}
Prior to Java 9, you would have used Class.newInstance
:在 Java 9 之前,您会使用
Class.newInstance
:
Object foo(Class type) throws InstantiationException, IllegalAccessException {
return type.newInstance();
}
...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. ...但它从 Java 9 开始被弃用,因为它抛出了构造函数抛出的任何异常,甚至是检查异常,但没有(当然)声明这些检查异常,有效地绕过了编译时检查异常处理。
Constructor.newInstance
wraps exceptions from the constructor in InvocationTargetException
instead. Constructor.newInstance
将构造函数中的异常包装在InvocationTargetException
。
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.一个更健壮的路线是通过
Class.getDeclaredConstructors
或Class.getConstructors
,它会带您使用java.lang.reflect
包中的反射内容,以找到参数类型与您打算提供的参数相匹配的构造函数。
Use:用:
type.newInstance()
For creating an instance using the empty costructor, or use the method type.getConstructor(..) to get the relevant constructor and then invoke it.对于使用空的 costructor 创建实例,或使用方法 type.getConstructor(..) 获取相关的构造函数然后调用它。
Yes, it is called Reflection.是的,它被称为反射。 you can use the Class
newInstance()
method for this.您可以为此使用 Class
newInstance()
方法。
使用 newInstance() 方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.