xiangpei
2025-04-18 ccadf9480d4e6a9dcc227a2a0b1f9ae0612e36fd
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
45
46
47
48
49
package com.monkeylessey.sys.domain.base;
 
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
 
/**
 * 用于获取泛型,因为泛型方法无法传入:List<String>.class 这样的Class,而泛型类可以,所以通过反射就能拿到
 *
 * @author 29443
 */
public abstract class TypeReference<T> {
    private final Type type;
 
    protected TypeReference() {
        Class<?> parameterizedTypeReferenceSubclass = findParameterizedTypeReferenceSubclass(this.getClass());
        Type type = parameterizedTypeReferenceSubclass.getGenericSuperclass();
        ParameterizedType parameterizedType = (ParameterizedType) type;
        this.type = parameterizedType.getActualTypeArguments()[0];
    }
 
    public Type getType() {
        return this.type;
    }
 
    @Override
    public boolean equals(Object obj) {
        return this == obj || obj instanceof TypeReference && this.type.equals(((TypeReference) obj).type);
    }
 
    @Override
    public int hashCode() {
        return this.type.hashCode();
    }
 
    @Override
    public String toString() {
        return "TypeReference<" + this.type + ">";
    }
 
    private static Class<?> findParameterizedTypeReferenceSubclass(Class<?> child) {
        Class<?> parent = child.getSuperclass();
        if (Object.class == parent) {
            throw new IllegalStateException("Expected TypeReference superclass");
        } else {
            // 递归找到直接继承TypeReference抽象类的Class
            return TypeReference.class == parent ? child : findParameterizedTypeReferenceSubclass(parent);
        }
    }
}