在java中,我可以使用类对象动态实例化该类型的类吗?
即。我想要这样的功能。
Object foo(Class type) {
// return new object of type 'type'
}
答案 0 :(得分:27)
您可以使用Class.newInstance
:
Object foo(Class type)
throws InstantiationException, IllegalAccessException {
return type.newInstance();
}
...但是假设有一个零参数构造函数。一个更健壮的路线是通过Class.getConstructor
或Class.getConstructors
,它会引导您使用java.lang.reflect
包中的反射内容。
答案 1 :(得分:2)
使用:
type.newInstance()
使用空的costructor创建实例,或使用方法type.getConstructor(..)获取相关的构造函数,然后调用它。
答案 2 :(得分:1)
是的,它被称为反射。你可以使用Class newInstance()
方法。
答案 3 :(得分:0)
使用newInstance()方法。