文章

获得泛型的真实类型

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

class MyClass {
}

class MyInvoke {
}

class Param<T1, T2> {
    class A {
    }

    class B extends A {
    }

    private Class<T1> entityClass;

    public Param() {
        Type superClass = getClass().getGenericSuperclass();
        System.out.println("当前类:" + getClass());
        System.out.println("当前类的直接父类:" + superClass);
        // getActualTypeArguments()返回表示此类型实际类型参数的Type对象的数组。[0]就是这个数组中第一个,也就是获得超类的泛型参数的实际类型。
        Type trueType = ((ParameterizedType) superClass).getActualTypeArguments()[0];
        System.out.println("超类的泛型参数的实际类型1 = " + trueType);
        trueType = ((ParameterizedType) superClass).getActualTypeArguments()[1];
        System.out.println("超类的泛型参数的实际类型2 = " + trueType);

        this.entityClass = (Class<T1>) trueType;
        System.out.println("entityClass = " + entityClass);

        B t = new B();
        // B的直接父类A
        superClass = t.getClass().getGenericSuperclass();

        System.out.println("B类的父类的泛型参数个数:" + ((ParameterizedType) superClass).getActualTypeArguments().length);
    }
}

class ClassDemo extends Param<MyClass, MyInvoke> {
    public static void main(String[] args) {
        ClassDemo classDemo = new ClassDemo();
    }
}
本文由作者按照 CC BY 4.0 进行授权