Sping获取泛型-GenericTypeResolver

young 837 2022-10-23

项目中需要获取类的父类或者某个实现接口上的泛型,使用ResolvableType获取则过于繁琐。

此时发现Spring提供了GenericTypeResolver工具类。

常用方法:

// 获取指定clazz继承或实现的genericIfc上的一个泛型
Class<?> resolveTypeArgument(Class<?> clazz, Class<?> genericIfc)
// 获取指定clazz继承或实现的genericIfc上的泛型数组
Class<?>[] resolveTypeArguments(Class<?> clazz, Class<?> genericIfc)
  

示例:

interface Event<T>{}

class A implements Event<Integer>{}

interface Person<T,R>{}

class Man implements Person<String, BigDecimal>{}

class C<X> {}

class D extends C<Double>{}

class E implements Event<String>,Person<Double,Short>{}

@Test
public void test(){
    Class<?> typeArgument1 = GenericTypeResolver.resolveTypeArgument(A.class, Event.class);
    System.out.println(typeArgument1); // class java.lang.Integer

    Class<?>[] typeArgument2 = GenericTypeResolver.resolveTypeArguments(Man.class, Person.class);
    for (Class<?> clazz : typeArgument2) {
      System.out.println(clazz); // class java.lang.String   class java.math.BigDecimal
    }
    Class<?> typeArgument3 = GenericTypeResolver.resolveTypeArgument(D.class, C.class);
    System.out.println(typeArgument3); // class java.lang.Double

    Class<?> typeArgument4 = GenericTypeResolver.resolveTypeArgument(E.class, Event.class);
    System.out.println(typeArgument4); // class java.lang.String

    Class<?>[] typeArgument5 = GenericTypeResolver.resolveTypeArguments(E.class, Person.class);
    for (Class<?> clazz : typeArgument5) {
      System.out.println(clazz);  // class java.lang.Double  class java.lang.Short
    }
}