public class TypeParameterResolver {
/**
* @return The field type as {@link Type}. If it has type parameters in the declaration,<br>
* they will be resolved to the actual runtime {@link Type}s.
*/
public static Type resolveFieldType(Field field, Type srcType) {
// 返回属性的类型,如果是泛型,则为这次的实际类型
Type fieldType = field.getGenericType();
// 返回其声明类型
Class<?> declaringClass = field.getDeclaringClass();
return resolveType(fieldType, srcType, declaringClass);
}
/**
* @return The return type of the method as {@link Type}. If it has type parameters in the declaration,<br>
* they will be resolved to the actual runtime {@link Type}s.
*/
public static Type resolveReturnType(Method method, Type srcType) {
Type returnType = method.getGenericReturnType();
Class<?> declaringClass = method.getDeclaringClass();
return resolveType(returnType, srcType, declaringClass);
}
/**
* @return The parameter types of the method as an array of {@link Type}s. If they have type parameters in the declaration,<br>
* they will be resolved to the actual runtime {@link Type}s.
*/
/**
* 解析方法入参
* @param method 目标方法
* @param srcType 目标方法所属的类
* @return 解析结果
*/
public static Type[] resolveParamTypes(Method method, Type srcType) {
// 取出方法的所有入参
Type[] paramTypes = method.getGenericParameterTypes();
// 定义目标方法的类或接口
Class<?> declaringClass = method.getDeclaringClass();
// 解析结果
Type[] result = new Type[paramTypes.length];
for (int i = 0; i < paramTypes.length; i++) {
// 对每个入参依次调用resolveType方法
result[i] = resolveType(paramTypes[i], srcType, declaringClass);
}
return result;
}
/**
* 解析变量的实际类型
* @param type 变量的类型
* @param srcType 变量所属于的类
* @param declaringClass 定义变量的类
* @return 解析结果
*/
private static Type resolveType(Type type, Type srcType, Class<?> declaringClass) {
if (type instanceof TypeVariable) { // 如果是类型变量,例如“Map<K,V>”中的“K”、“V”就是类型变量。
return resolveTypeVar((TypeVariable<?>) type, srcType, declaringClass);
} else if (type instanceof ParameterizedType) { // 如果是参数化类型,例如“Collection<String>”就是参数化的类型。
return resolveParameterizedType((ParameterizedType) type, srcType, declaringClass);
} else if (type instanceof GenericArrayType) { // 如果是包含ParameterizedType或者TypeVariable元素的列表
return resolveGenericArrayType((GenericArrayType) type, srcType, declaringClass);
} else {
return type;
}
}
public class ClassA<K,V> {
public Map<K,V> map;
}
public class SubClassA<T> extends ClassA {
}
public class TestType {
SubClassA<Long> sa = new SubClassA();
}
Field field = SubClassA.class.getSuperclass().getDeclaredField("map");
System.out.println(field.getGenericType());
System.out.println(field.getGenericType() instanceof ParameterizedType);
System.out.println(field.getType());
--------------------------------
java.util.Map<K, V>
true
interface java.util.Map
TypeParameterResolver它是一个工具类,提供了一系列静态方法来解析指定类中的宇段、方法返回值或方法参数的类型。 TypeParameterResolver 中各个静态方法之间的调用关系大致如图 2-11 所示,为保持清晰,其中递归调用没有表现出来,在后面的代码分析过程中会进行强调。public class TypeParameterResolver { /** * @return The field type as {@link Type}. If it