ParameterizedType及其方法详解


先贴一段代码:

public class AbstractService implements MyService {

    @Autowired
    private  MyMapper mapper;

    // 当前泛型真实类型的Class
    private  Class modelClass;

    public AbstractService() {
        ParameterizedType parameterizedType = (ParameterizedType) this.getClass().getGenericSuperclass();
        modelClass = (Class) parameterizedType.getActualTypeArguments()[0];
    }
}

我们来了解一下Type这个接口。
Type是Java中所有类型的通用超级接口。 这些类型包括基本类型,参数化类型,数组类型,类型变量。
这里的类型其实是某个类的对应的Class名。
如:Integer.class, Double.class, Person.class

public class Main {
    public static void main(String[] args) {
        Field[] fields = Person.class.getDeclaredFields();
        for (Field field : fields) {
            if (field.getGenericType() instanceof ParameterizedType) {
                ParameterizedType genericType = (ParameterizedType) field.getGenericType();
                Type[] arguments = genericType.getActualTypeArguments();
                for (Type type : arguments) {
                    System.out.println(type);
                }
            }
        }
    }
}

class Person {
    List integerList;
    List doubleList;
    List
mainList; } 结果: java.lang.Integer java.lang.Double Main

所以我们只要得到Type对象,就得到了泛型类

再来看ParameterizedType 接口,它是Type接口的子接口,表示参数化类型。如:List< Integer >; 这个接口中有个方法getActualTypeArguments()它可以获取某个类的所有Type对象(即可以获取某个类的所有泛型)。

例如:父类Person的泛型有两个

public class Person {
}

我们可以如下方式获取父类中的泛型:

public class Student extends Person {

    public static void main(String[] args) {
        Class clazz = Student.class;
        //获取带泛型的类型
        ParameterizedType superclass = (ParameterizedType) clazz.getGenericSuperclass();
        Type[] arguments = superclass.getActualTypeArguments();
        for (Type argument : arguments) {
            System.out.println(argument);
        }
    }
    
}

结果:
    Student
    Integer

获取父类泛型的类型的方式总结:
1.构造子类Class对象
2.获取带泛型的父类的ParameterizedType对象
3.获取父类的Type数组(Type数组中保存了父类的泛型的类型)

参考:https://blog.csdn.net/weixin_45359574/article/details/105559327