从类对象实例化类

时间:2010-06-14 11:23:08

标签: java class new-operator

在java中,我可以使用类对象动态实例化该类型的类吗?

即。我想要这样的功能。

Object foo(Class type) {
    // return new object of type 'type'
}

4 个答案:

答案 0 :(得分:27)

您可以使用Class.newInstance

Object foo(Class type)
throws InstantiationException, IllegalAccessException {
    return type.newInstance();
}

...但是假设有一个零参数构造函数。一个更健壮的路线是通过Class.getConstructorClass.getConstructors,它会引导您使用java.lang.reflect包中的反射内容。

答案 1 :(得分:2)

使用:

type.newInstance()

使用空的costructor创建实例,或使用方法type.getConstructor(..)获取相关的构造函数,然后调用它。

答案 2 :(得分:1)

是的,它被称为反射。你可以使用Class newInstance()方法。

答案 3 :(得分:0)

使用newInstance()方法。