简体   繁体   English

如何在泛型类中使用getConstructor?

[英]How to use getConstructor with Generic class?

This is my first brush with reflection and generics in Java so please pardon my ignorance. 这是我第一次使用反射和Java语言泛型,因此请原谅我的无知。 I am trying to instantiate a class using reflection and generics but getting error in my toy program. 我试图使用反射和泛型实例化一个类,但是在我的玩具程序中出现错误。 The goal is to instantiate with constructor of inst class. 目的是用inst类的构造函数实例化。

Code: 码:

/*
*This is the builder class to build an instance
*/
package generics.expClassT;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

public class builder {
    public static<E> E createInst(Class<E> c) throws InstantiationException, IllegalAccessException {
        //Class<?>[] type = new Class<?>[1];
        //type[0] = inst.class;
        try {
            Constructor<E> ctor = c.getConstructor(c); //c.getConstructor(type);
            return (ctor.newInstance("Testing"));
        } catch (NoSuchMethodException | SecurityException | IllegalArgumentException | InvocationTargetException e) {
            e.printStackTrace();
            return null;
        }
    }
}


/*
* This is the class for which we need an instance
*/
package generics.expClassT;
public class inst {
private String var;
public inst(String s) { 
    this.var = s;
}
public String getVar() {
    return var;
}

public static void main(String args[]){
    inst instObj;
    try {
        instObj = builder.createInst(inst.class);
        System.out.println(instObj.getVar());
    } catch (InstantiationException | IllegalAccessException e) {
        //e.printStackTrace();
    }

}
}

Exception: 例外:

java.lang.NoSuchMethodException: generics.expClassT.inst.<init>(generics.expClassT.inst)
at java.lang.Class.getConstructor0(Class.java:2800)
at java.lang.Class.getConstructor(Class.java:1708)
at generics.expClassT.builder.createInst(builder.java:15)
at generics.expClassT.inst.main(inst.java:19)
Exception in thread "main" java.lang.NullPointerException
at generics.expClassT.inst.main(inst.java:20)

Thank you in advance for your time and assistance!! 预先感谢您的时间和帮助!!

Constructor<E> ctor = c.getConstructor(c); should be Constructor<E> ctor = c.getConstructor(String.class); 应该是Constructor<E> ctor = c.getConstructor(String.class);

From the JavaDocs JavaDocs

Returns a Constructor object that reflects the specified public constructor of the class represented by this Class object. 返回一个构造函数对象,该对象反映此Class对象表示的类的指定公共构造函数。 The parameterTypes parameter is an array of Class objects that identify the constructor's formal parameter types, in declared order . parameterTypes参数是Class对象的数组,这些类按声明的顺序标识构造函数的形式参数类型 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. 如果此Class对象表示在非静态上下文中声明的内部类,则形式参数类型包括显式的封闭实例作为第一个参数。

The constructor to reflect is the public constructor of the class represented by this Class object whose formal parameter types match those specified by parameterTypes. 要反映的构造函数是此Class对象表示的类的公共构造函数,其正式参数类型与parameterTypes指定的类型相匹配。

Parameters: 参数:
parameterTypes - the parameter array parameterTypes-参数数组

This, basically, means, that getConstructor(Class...) expects you to pass the class types that have been defined by the classes constructor, in your case public Inst(String s) 基本上,这意味着getConstructor(Class...)希望您传递由类构造函数定义的类类型,在您的情况下为public Inst(String s)

Builder 建造者

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

public class Builder {

    public static <E> E createInst(Class<E> c) throws InstantiationException, IllegalAccessException {
        //Class<?>[] type = new Class<?>[1];
        //type[0] = inst.class;
        try {
            Constructor<E> ctor = c.getConstructor(String.class); //c.getConstructor(type);
            return (ctor.newInstance("Testing"));
        } catch (NoSuchMethodException | SecurityException | IllegalArgumentException | InvocationTargetException e) {
            e.printStackTrace();
            return null;
        }
    }

}

Inst 研究所

public class Inst {

    private String var;

    public Inst(String s) {
        this.var = s;
    }

    public String getVar() {
        return var;
    }
}

Main 主要

public class Test {

    public static void main(String[] args) {
        Inst instObj;
        try {
            instObj = Builder.createInst(Inst.class);
            System.out.println(instObj.getVar());
        } catch (InstantiationException | IllegalAccessException e) {
            //e.printStackTrace();
        }
    }

}

You might like to have a read through Code Conventions for the Java TM Programming Language , it will make it easier for people to read your code and for you to read others 您可能希望通读Java TM编程语言的代码约定 ,这将使人们更容易阅读您的代码,并使您阅读其他代码更容易

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM