shikeying
2024-01-11 3b67e947e36133e2a40eb2737b15ea375e157ea0
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
package com.walker.infrastructure.utils;
 
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
 
public class GenericTypeUtils {
 
    /**
     * 返回给定对象的泛型类型,默认返回第一个泛型(可能存在多个)。
     * @param clazz
     * @return
     * @date 2022-11-16
     */
    public static Class getSuperClassGenericType(Class clazz){
        return getSuperClassGenericType(clazz, 0);
    }
 
    public static Class getSuperClassGenericType(Class clazz, int index){
        Type genType = clazz.getGenericSuperclass();
 
        if (!(genType instanceof ParameterizedType)) {
//          log.warn(clazz.getSimpleName() + "'s superclass not ParameterizedType");
            return Object.class;
        }
 
        Type[] params = ((ParameterizedType)genType).getActualTypeArguments();
 
        if ((index >= params.length) || (index < 0)) {
//          log.warn("Index: " + index + ", Size of " + clazz.getSimpleName() + "'s Parameterized Type: " + params.length);
            return Object.class;
        }
        if (!(params[index] instanceof Class)) {
//          log.warn(clazz.getSimpleName() + " not set the actual class on superclass generic parameter");
            return Object.class;
        }
        return (Class)params[index];
    }
}