zoukankan      html  css  js  c++  java
  • 关于在泛型参数反射时的问题

    public class A<T> {
    private Class<T> entityClass;

    @SuppressWarnings({ "unchecked", "rawtypes" })
    public A() {
    System.out.println(this.toString());
    Type genType = getClass().getGenericSuperclass();
    System.out.println("genType=====" + genType);
    Type[] params = ((ParameterizedType) genType).getActualTypeArguments();// 这个其实获得的是泛型参数,所以这里的要求是必须给这个类加泛型
    // entityClass = (Class) params[0];
    // System.out.println(entityClass);
    for (Type t : params) {
    entityClass = (Class) t;
    System.out.println(entityClass);
    }
    // 结果class java.lang.Integer class java.lang.Double

    }

    public static void main(String[] args) {

    C a = new C();//C是A的子类
    }

    这段代码是正确的,但是我想有人肯定遇过这种情况:  java.lang.Class cannot be cast to java.lang.reflect.ParameterizedType 

      出现这个问题的根本原因是因为你的A类没有泛型参数,Type[] params = ((ParameterizedType) genType).getActualTypeArguments();这里的genType是A,当他强转为(ParameterizedType)的时候,这时候后面的方法getActualTypeArguments()是获取到A类的类型参数的集合,如果你的A类没有类型参数,就会报上面那个异常

  • 相关阅读:
    goreplay~基本知识
    goreplay~http输出队列
    goreplay~拦截器设置
    goreplay~流量变速
    goreplay~http过滤参数
    goreplay~文件输出解析
    goreplay~http输出工作线程
    Antlr4 语法解析器(下)
    2021最新版Eclipse的下载和使用
    MySQL中drop、truncate和delete的区别
  • 原文地址:https://www.cnblogs.com/Booker808-java/p/8081620.html
Copyright © 2011-2022 走看看