TypeVariable
TypeVariable 简单理解
是什么
泛型类型参数,比如 <T>、<E> 中的 T 和 E
核心特点
- 代表不确定的类型
- 在编译时是占位符
- 运行时需要解析为具体类型
简单例子
// T 就是 TypeVariable
class Box<T> {private T value; // T 等待被具体类型替换
}// 使用时确定具体类型
Box<String> box = new Box<>(); // T 变成 String
Box<Integer> box2 = new Box<>(); // T 变成 Integer
常见 TypeVariable
List<T> // T 是 TypeVariable
Map<K, V> // K 和 V 都是 TypeVariable
Comparable<T> // T 是 TypeVariable
一句话总结
泛型中的字母占位符,使用时被真实类型替换
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);
}
一句话理解
先检查是不是泛型参数,如果是就转成对应类型来使用
