Java中的通配符和类型参数范围 [英] Wildcard and type pameter bounds in java
问题描述
考虑这种情况:
class A {}
class B<T extends A, E extends T> {
B<?, A> b;
B<?, ? extends A> b2;
}
据我了解类型界限,在这种情况下,两个<$的有效上限c $ c> T 和 E
是类A
。所以问题来了:为什么javac在字段 b
的声明中不接受A类作为参数,而是接受通配符
?在字段
? b2
的声明中扩展A
As I understand type bounds, in this case effective upper bounds of both T
and E
is class A
. So the question: why javac doesn't accept class A as argument in declaration of field b
, but accepts wildcard
? extends A
in declaration of field b2
?
推荐答案
具有以下类别:
class A {}
class C extends A {}
class B<T extends A, E extends T> {}
这样想:
E扩展T扩展A
用 B , A>
然后 T-> ?
和 E-> A
A扩展了吗?扩展A
其中?
可以是 A
,例如 C
。
A扩展C扩展A
显然是无效的。
这就是为什么这是编译错误。
E extends T extends A
With B<?,A>
then T -> ?
and E -> A
A extends ? extends A
Where the ?
could be any subclass of A
, let's say C
.
A extends C extends A
is clearly invalid.
So that's why it's a compile error.
Eclipse 4.9.0编译器不同意javac 8u和Intellij,并且对于 B<?,A>
。我假设这是Eclipse编译器中的错误,但是我没有咨询JLS来确认这一点。
Eclipse 4.9.0 compiler disagreed with javac 8u and Intellij and did not emit a compile error for the generic arguments in B<?,A>
. I assume this is a bug in the Eclipse compiler but I have not consulted the JLS to confirm this.
class B<T extends A, E extends T> {
B<?, A> b; // <-- Eclipse does NOT emit a compile error
B<?, ? extends A> b2;
}
此假定错误已报告此处。
这篇关于Java中的通配符和类型参数范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!