java - Java泛型中类型参数的前向引用

标签 java generics

根据 Java 泛型常见问题解答 http://www.angelikalanger.com/GenericsFAQ/FAQSections/TypeParameters.html#FAQ302 不能以这种方式向前引用类型参数

<A extends B, B> // error

但还是可以的

<A extends List<B>, B> // ok

这两个例子都是用最新的jdk 1.6.0_24验证的.

我的问题是,在语言规范中,这是指定的、暗示的或可扣除的(即,如果它不真实,其他事情可能会爆炸)。我到处都找不到。

更新

在javac7中,是允许的。直觉上,类型参数的顺序无关紧要;类型系统要求类型变量之间没有循环依赖:<A extends B, B extends A> .以前,这可以通过禁止前向引用来保证。显然 javac 7 得到了改进以放宽排序,同时检测循环而不考虑排序。

最佳答案

我不确定这是真的。我查看了 Java Language Specification在 §6.3 中有关于类型参数范围的讨论:

The scope of an interface's type parameter is the entire declaration of the interface including the type parameter section itself. Therefore, type parameters can appear as parts of their own bounds, or as bounds of other type parameters declared in the same section.

The scope of a method's type parameter is the entire declaration of the method, including the type parameter section itself. Therefore, type parameters can appear as parts of their own bounds, or as bounds of other type parameters declared in the same section.

The scope of a constructor's type parameter is the entire declaration of the constructor, including the type parameter section itself. Therefore, type parameters can appear as parts of their own bounds, or as bounds of other type parameters declared in the same section.

(我的重点)。

这表明在声明中

那个BA extends B时确实在范围内.

此外,JLS 的 §4.4 说,当提到类型变量的绑定(bind)时,

The bound consists of either a type variable, or a class or interface type T

这表明不仅是 B<A extends B, B> 范围内, 但它是 A 上的完全合法约束.

最后,最重要的是,这段代码在 javac 中编译:

public class Test {
     public static <A extends B, B> A test(B obj) {
         return null;
     }
}

所以我非常确定这是完全合法的 Java 代码,并且您链接到的示例要么是错误的,要么是在引用其他内容。

希望这对您有所帮助,如果我的推理存在缺陷,请告诉我!

关于java - Java泛型中类型参数的前向引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5201687/

相关文章:

java - 这个问题的创造性设计模式?

java - 检查泛型java中的引用类型

java - RMI 客户端无法查找服务器 - java.rmi.UnmarshalException

java - 我可以在 Java 中将变量命名为 'public' 以进行 JSON 序列化/反序列化吗?

java - 根据通用类型创建对象

java - 实例化泛型类时传递类型变量

c# - 通用比较抛出 "At least one object must implement IComparable."

java - 尝试学习泛型,有没有办法查看一个泛型对象是否比另一个更大或更小?

java - Java中将字节数组转换为int数组,通过ByteBuffer到IntBuffer,不截断

java - Java线程ID在多个线程池中是否唯一?