TypeVariable 检测与转换 type instanceof TypeVariable (TypeVariable<?>) type
TypeVariable 检测与转换
type instanceof TypeVariable
检查 type 是不是泛型参数(如 T、E)
class Box<T> { } // T 是 TypeVariableType type = Box.class.getTypeParameters()[0];
boolean isTypeVar = type instanceof TypeVariable; // true
(TypeVariable<?>) type
把 type 转成 TypeVariable 类型来使用
TypeVariable<?> typeVar = (TypeVariable<?>) type;
String name = typeVar.getName(); // 得到 "T"
完整流程
if (type instanceof TypeVariable) {// 确定是泛型参数后,强制转换TypeVariable<?> typeVar = (TypeVariable<?>) type;// 现在可以调用 TypeVariable 的方法return resolveTypeVar(typeVar, srcType, declaringClass);
}
一句话理解
先检查是不是泛型参数,如果是就转成对应类型来使用
