Java 从类对象实例化类
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3036777/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
instantiate class from class object
提问by akula1001
In java, can I use a class object to dynamically instantiate classes of that type?
在java中,我可以使用类对象动态实例化该类型的类吗?
i.e. I want some function like this.
即我想要一些这样的功能。
Object foo(Class type) {
// return new object of type 'type'
}
采纳答案by T.J. Crowder
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 及更高版本中,如果有一个声明的零参数(“nullary”)构造函数,您将使用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. Constructor.newInstance
wraps exceptions from the constructor in InvocationTargetException
instead.
...但它从 Java 9 开始被弃用,因为它抛出了构造函数抛出的任何异常,甚至是检查异常,但没有(当然)声明这些检查异常,有效地绕过了编译时检查异常处理。而是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
or Class.getConstructors
,它会带你使用java.lang.reflect
包中的反射内容,找到一个构造函数,其参数类型与你打算给它的参数相匹配。
回答by Eyal Schneider
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(..) 获取相关的构造函数然后调用它。
回答by akf
Yes, it is called Reflection. you can use the Class newInstance()
method for this.
是的,它被称为反射。您可以newInstance()
为此使用 Class方法。
回答by GG.
use newInstance() method.
使用 newInstance() 方法。