有没有办法在构造函数中找到泛型类型?
public class geneticarg {
public static void main(String[] args) {
a<String> a1 = new a<String>("a");
a<String> a2 = new a<String>(null); // gives NPE
System.out.println(a1.getClazz());
}
}
class a<T> {
private Class<T> clazz;
private T element;
public a(T clazz) {
this.clazz = (Class<T>) clazz.getClass();
this.element = clazz;
// what if clazz is null ?
}
//getter and setter
}
编辑:不一定总是 String 来。