[up-cast case] - Cast a type variable to its upper bound for capture conversion
Consider this example:
<X extends List<?>> void foo(Class<X> clazz) throws Exception
{
List<?> instance = clazz.newInstance();
bar(instance);
}
<T> void bar(List<T> list) { ... }
We know that capture conversion is done in expression `b(instance)` - the type of `instance`, `List<?>`, is converted to `List<W>` for some unknown type W; then `T` in `bar()` is infer as `T=W`.
The return type of `clazz.newInstance()` is actually `X`, the type variable with upper bound `List<?>`. However, this won't work -
X instance = clazz.newInstance();
bar(instance);
because according to spec, capture conversion only applies to wildcard parameterized types; on any other type, (e.g. `X` here), the type is left as is.
Now type inference fails on `bar(instance)`, because it cannot find a `T` so that `X` is a subtype of `List<T>`.
This problem can be viewed as a flaw of the spec; the workaround is to cast the type variable to the upper bound so that capture conversion can be applied -
X instance = clazz.newInstance();
bar( (List<?>) instance );
--
Zhong Yu
bayou.io