java - 创建 TypeVariable 实例

标签 java reflection type-variables

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

从上面的引用中我了解到有两种实例化:

  1. 创建类型变量(我不明白)
  2. 代表类型变量的多个实例的实例化

谁能解释一下它们之间的区别吗?

最佳答案

考虑下面的类:

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 ,即使它们代表相同类型的变量。

Ideone demo

关于java - 创建 TypeVariable 实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39312452/

相关文章:

c# - 在您的业务逻辑中使用反射是好的做法吗?

java - Class<?>#getTypeParameters() 的返回类型是什么?

Haskell:实现 "randoms"(又名,不明确的类型变量)

java - 如何在 Primefaces 数据表过滤器上保持 session

java - 表达式的类型必须是数组类型,但它解析为字符串 | java

java - 水平滚动条不适用于 Java Swing 中的 JTable

java - 通用类创建

java - 如何将复选框添加到警报对话框?

c# - 判断对象是否是泛型基类的实例,任意泛型类型

c# - 从事件处理程序确定发件人对象