JAVA如何在类中使用ParameterizedType获取泛式类型

在类中使用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,也是不相等的。

阅读 12.6k
2 个回答

创建一个类继承Demo<T>,使用

 Type superClass = getClass().getGenericSuperclass();
 Type type = ((ParameterizedType) superClass).getActualTypeArguments()[0];

得到泛型类型。

按照一楼的使用Type superClass = getClass().getGenericSuperclass();
但同时你测试的时候需要使用匿名内部类的实现,注意MyDemo最后的{},使MyDemoDemo$0匿名的,使其父类是Demo<String>,而不是Demo<T>。
注:这个测试最终什么都打印不出来,因为String.class.newInstance()是空字符串

public class Demo<T> {

    private Class<T> clazz;

    public T getDemo() throws InstantiationException, IllegalAccessException{
        Type superClass = getClass().getGenericSuperclass();
        if(superClass instanceof ParameterizedType){
            Type type = ((ParameterizedType) superClass).getActualTypeArguments()[0];
            this.clazz = (Class<T>) type;
        }else{
            System.out.println("不相等");
        }
        return clazz.newInstance();
    }

    public static void main(String[] args) throws IllegalAccessException, InstantiationException {
        Demo<String> MyDemo = new Demo<String>() {
        };
        String str = MyDemo.getDemo();
        System.out.println(str);
    }
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题