java - Class.getConstructor函数参数

标签 java class reflection getconstructor

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

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() 返回该类的构造函数对象,但是 (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}); 返回接受一个且仅一个 int 参数或 NoSuchMethodException 的构造函数 如果它不存在。

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

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

关于java - Class.getConstructor函数参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48668919/

相关文章:

java - 登录在我的 servlet 程序中不起作用

java - 底层类结构更改后反序列化对象

python - 自动关闭 kivy 中的弹出窗口

c++ - 具有模板化父类的派生类

java - 加载从目录中的 jar 扩展另一个类的类

java - Mockito 空指针异常

与整数参数一起使用时,Java Color 创建会抛出 IllegalArgumentException

css - 选择基于 "class"声明的存在

java - 使用反射获取私有(private)非原始字段的值

.net - 如何在派生类上动态调用静态方法