下界的通配符不针对上限类型参数进行检查 [英] Lower bounded wildcard not checked against upper bounded type parameter
问题描述
源代码:
抽象类A< K extends Number>
{
public abstract< M> A< ;? super M> useMe(A<?super M> k);
}
成功编译
它是如何工作的,为什么编译? M是任何类型,为什么它可以被使用?应该是:< M扩展数字>
?
这将无法编译:
抽象类A&K;扩展数字>
{
public abstract< M> A< ;? super M> useMe(A< M> k);
错误讯息:
类型参数M不在变量K的范围内,其中M,K是类型变量:
M extends在方法useMe(A)中声明的对象
K扩展在A类中声明的数字
有什么区别?
I wonder why does this piece of code compile successfully?
Source code:
abstract class A<K extends Number>
{
public abstract <M> A<? super M> useMe(A<? super M> k);
}
Compiled successfully
How does it work and why does this compile? M is any type, so why it can be used?. Should it be: <M extends Number>
?
This will not compile:
abstract class A<K extends Number>
{
public abstract <M> A<? super M> useMe(A<M> k);
}
Error message:
type argument M is not within bounds of type variable K where M, K are type variables: M extends Object declared in method useMe(A) K extends Number declared in class A
What is the difference?
This compiler behavior was discussed on this Eclipse bug. Originally, the Eclipse compiler did error for the expression in your example, while javac did not. Although I haven't yet searched the JLS directly, the consensus seems to be that there is nothing in the spec requiring lower bounded wildcards to be checked against type parameter bounds. In this situation it's ultimately left to the caller to assign a type that satisfies the constraints (as surmised by Stephan Herrmann on that post).
这篇关于下界的通配符不针对上限类型参数进行检查的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!