在类中使用ParameterizedType获取类的实体类的泛式类
有以下代码:
public class Demo<T> {
private Class<T> clazz;
public T getDemo() throws InstantiationException, IllegalAccessException{
return clazz.newInstance();
}
public static void test() throws InstantiationException, IllegalAccessException{
String str = new Demo<String>().getDemo();
}
}
现在我要调用test()方法,获取一个String实体类,但当我调用的时候会抛出NullPointerException指clazz为空值,无法调用。那么这时候我改一下getDemo方法,使用ParameterizedType获取泛式并且赋值
public T getDemo() throws InstantiationException, IllegalAccessException{
Type superClass = getClass();
if(superClass instanceof ParameterizedType){
Type type = ((ParameterizedType) superClass).getActualTypeArguments()[0];
this.clazz = (Class<T>) type;
}else{
System.out.println("不相等");
}
return clazz.newInstance();
}
但是这时候获取到的superClass为 Demo ,并不是 Demo<String>,因此superClass instanceof ParameterizedType不成立,控制台输出"不相等",clazz仍未null,所以想问一下大家这种情况下要怎么样才能获取到泛型的类呢?
注意就算把Type superClass = getClass();改为 Type superClass = getClass().getGenericSuperclass(); 也是没有用的,因为Demo类不继承其他类,所以获取到的是Object,也是不相等的。
创建一个类继承Demo<T>,使用
得到泛型类型。