What are the formal conditions for a wildcard parameter in a Java generic type to be within its bounds?

点点圈 提交于 2019-11-30 18:46:46

JLS on generics is incomplete, and you caught another hole in it. Lower bound on type variables is barely discussed, and I don't see any restriction in spec either on X having upper bound Number and lower bound Runnable. They probably left it out.

Intuitively, there must be at least one possible type that satisfies both upper bound and lower bound of a type variable, otherwise the variable and all types using the variable would be useless. Since this is almost certainly a programming mistake, compile should fail.

It's easy to check whether upper bound and lower bound make an empty set of types. All super types of the lower bound are known; at least one of them should be the upper bound, otherwise there is no type that's within both bounds.

--

The two Foo<? extends A> cases are well defined in the spec. With capture conversion, we have new type variable X with upper bound A & Number, and the spec says for an upper bound V1&...&Vm

It is a compile-time error if for any two classes (not interfaces) Vi and Vj,Vi is not a subclass of Vj or vice versa.

Therefore if A=Thread, capture conversion fails.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!