下界的通配符不针对上限类型参数进行检查 [英] Lower bounded wildcard not checked against upper bounded type parameter

查看:120
本文介绍了下界的通配符不针对上限类型参数进行检查的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



源代码:

 抽象类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类中声明的数字



有什么区别?

解决方案这个编译器行为在这个Eclipse错误上进行了讨论。最初,Eclipse编译器在你的例子中为表达式做了错误,而javac没有。虽然我还没有直接搜索JLS,但我们的共识似乎是规范中没有任何内容要求使用更低的有界通配符来检查类型参数边界。在这种情况下,最终留给调用者来分配满足约束条件的类型(正如Stephan Herrmann在该帖子中所猜测的那样)。

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆