首页 > 其他分享 >泛型参数类的获取

泛型参数类的获取

时间:2023-02-08 19:00:10浏览次数:36  
标签:paramType 获取 参数 泛型 ParameterizedType public

泛型参数类不能通过实例化一个对象获取,比如 A<T> a=new A();因为使用了泛型的代码在运行期间相关的泛型参数的类型会被擦除,我们无法在运行期间获知泛型参数的具体类型(所有的泛型类型在运行时都是Object类型)

获取的方式

1、创建匿名内部类

  public Test {

        public static void main(Strin[] args ) {

    A<T> a=new A(){};

    Type t=a.getClass().getGenericSuperclass();

    //下面就可以将t获取到自己想要的泛型参数或做别的处理,这里的t的类型是ParameterizedType

  }

}

2、继承

public class Student extends Person<String> {
}
。。。
Student aa = new Student();
Class<?> classType = aa.getClass();
Type type = classType.getGenericSuperclass();
if (type instanceof ParameterizedType) {
  ParameterizedType paramType = (ParameterizedType) type;
  log.info("paramType.getTypeName(): {}", paramType.getTypeName());
  if (ArrayUtil.isNotEmpty(paramType.getActualTypeArguments())) {
    log.info("paramType.getActualTypeArguments(): {}", paramType.getActualTypeArguments()[0]);
  }
}

3、作为类的属性方式

public Test{

  public A<T> a; //这里必须是public不然无法获取到类型

  Parameterized pt=Test.class.getFiled("a").getGenericType();

}

标签:paramType,获取,参数,泛型,ParameterizedType,public
From: https://www.cnblogs.com/sts-z/p/17102979.html

相关文章