从类对象实例化类

问题描述 投票:19回答:4

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

即我想要这样的功能。

Object foo(Class type) {
    // return new object of type 'type'
}
java class new-operator
4个回答
29
投票

在Java 9及之后的版本中,如果有一个声明的零参数(“空”)构造函数,则可以使用Class.getDeclaredConstructor()来获取它,然后在其上调用Class.getDeclaredConstructor()

newInstance()

在Java 9之前,您应该使用newInstance()

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

...但是从Java 9开始不推荐使用,因为它抛出了构造函数抛出的任何异常,甚至是检查过的异常,但是(当然)没有声明那些检查过的异常,有效地绕过了编译时检查过的异常处理。 Class.newInstance将构造函数的异常包装在Class.newInstance中。

以上两者均假设有一个零参数构造函数。一种更可靠的方法是遍历Object foo(Class type) throws InstantiationException, IllegalAccessException { return type.newInstance(); } Constructor.newInstance,这将带您使用InvocationTargetException包中的Reflection东西,以找到参数类型与要提供的参数匹配的构造函数。


2
投票

用途:

Class.getDeclaredConstructors

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


1
投票

是的,它称为反射。您可以为此使用Class Class.getDeclaredConstructors方法。


-1
投票

使用newInstance()方法。

© www.soinside.com 2019 - 2024. All rights reserved.