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];
|
}
|
}
|