Class.getConstructor 函数参数

Class.getConstructor function parameters

我正在研究这段代码并卡在注释行中:

protected <T> T creaOggetto(Class<T> classe, int id) {
    try {
        Package pacchetto = classe.getPackage();
        String nomePacchetto = pacchetto.getName();
        String nomeClasse = classe.getSimpleName();
        String nomeClasseRisultato = nomePacchetto + ".impl." + nomeClasse + "Impl";
        Class<?> classeRisultato = Class.forName(nomeClasseRisultato);
        Constructor<?> costruttore = classeRisultato.getConstructor(new Class[] {int.class});

        @SuppressWarnings("unchecked")
        T risultato = (T)costruttore.newInstance(new Object[] {id});

        return risultato;
    } catch (Throwable throwable) {
        throwable.printStackTrace();
    }
    return null;
}

我知道 getConstructor() returns 的构造函数对象 class 但是 (new Class[] {int.class}) 让我很困惑,他的目的是什么?

根据 Java 文档:

public Constructor<T> getConstructor(Class<?>... parameterTypes) throws NoSuchMethodException, SecurityException

Returns a Constructor object that reflects the specified public constructor of the class represented by this Class object. The parameterTypes parameter is an array of Class objects that identify the constructor's formal parameter types, in declared order. If this Class object represents an inner class declared in a non-static context, the formal parameter types include the explicit enclosing instance as the first parameter.

因此,classeRisultato.getConstructor(new Class[] {int.class}); returns 构造函数接受一个且仅接受一个 int 参数或 NoSuchMethodException 如果它不存在。

在您发布的代码中,请注意,使用该构造函数,它创建了一个传递 id 的 class 的新实例,即实际的 int 参数:

T risultato = (T)costruttore.newInstance(new Object[] {id});

getConstructor(new Class[]);方法接受一个 Classes 数组,代表你想要获取的构造函数的参数。 例如,如果您在 class X 中有一个构造函数,

public X(int a, int b)

您可以使用 X.getClass().getConstructor(new Class[] {int.class, int.class}); 获得上述构造函数 数组中的两个 int.class 参数表示构造函数接收的两个整数。

Java Documentation

由于可能存在多个构造函数,调用Class.getConstuctor.

时需要指定构造函数的签名才能得到你想要的构造函数

签名包括构造函数的类型参数。签名还包括方法名,但对于构​​造函数,方法名在源代码中始终是 class 名称,在编译代码中始终是“”,因此您无需指定。

因此,如果您有新的 Class[] {int.class},那么您就是在说签名包含类型为 "int" 的单个参数。这意味着您需要构造函数 X(int x) for class name X(请注意,重要的只是参数的类型,而不是参数变量的名称)。

另请注意,int.class 解析为 java.lang.Integer.TYPE,用于表示原始类型 "int"。