official documentation TypeVariable
确实令人困惑,首先它指定:
A type variable is created the first time it is needed by a reflective method
和
Repeated creation of a type variable has no effect
所以我的理解是,只有一个 TypeVariable
实例在运行时表示类型变量,例如:
class A<T> {}
我们将拥有一个在运行时代表 T
的类型变量
实例。
但是文档添加了:
Multiple objects may be instantiated at run-time to represent a given type variable. Even though a type variable is created only once, this does not imply any requirement to cache instances representing the type variable. However, all instances representing a type variable must be equal() to each other
从上面的引用中我了解到有两种实例化:
- 创建类型变量(我不明白)
- 代表类型变量的多个实例的实例化
谁能解释一下它们之间的区别吗?
最佳答案
考虑下面的类:
class Ideone<T> {
List<T> getList() { ... }
}
这就是说代表 <T>
的类型变量关于类(class)和<T>
方法上的不一定是同一个实例:
TypeVariable onClass = Ideone.class.getTypeParameters()[0];
TypeVariable onMethod = Ideone.class.getDeclaredMethod("getList").getReturnType().getTypeParameters()[0];
System.out.println(onClass == onMethod);
打印 false
,即使它们代表相同类型的变量。
关于java - 创建 TypeVariable 实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39312452/