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

前端 未结 1 1521
感动是毒
感动是毒 2021-01-04 12:24

With parameterized types in Java, how do the rules that check if a parameter is within its bound work exactly for wildcards?

Given a class like this:

相关标签:
1条回答
  • 2021-01-04 13:17

    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.

    0 讨论(0)
提交回复
热议问题