generic compile problem

Alex Buckley alex.buckley at oracle.com
Tue Dec 11 15:02:00 PST 2012


Can Class<Generic> be cast to Class<? extends Generic<?>>  ?

In turn, is Class<Generic> provably distinct from Class<? extends 
Generic<?>>  (given that their erasures are the same)  ?

In turn, is 'Generic' provably distinct from '? extends Generic<?>>'  ?

No, because |Generic| <: |Generic<?>|.

(JLS3 was not clear on this point. If both type arguments were ground 
types, JLS3 could prove them distinct and stop the cast, e.g. 
Class<String> can never be cast to Class<Integer> because Class<String> 
is distinct from Class<Integer> because String is distinct from Integer. 
However, JLS3 could not handle one or two wildcard type arguments. JLS7 
takes the upper bound of a wildcard type argument - Generic<?> - and 
considers it against the ground type argument - Generic - to conclude 
that the type arguments are basically related.)

Therefore, there is no need for a compile-time error.

Since Class<Generic> is not a subtype of Class<? extends Generic<?>>, 
the cast is unchecked, and a compile-time unchecked warning is due.

Alex

On 12/11/2012 1:59 PM, Radim Kolar wrote:
> i sent wrong example. This one is right, compiles only in eclipse.
>
> class Generic<T> {}
> public class Casting {
>      void test() {
>          Class<? extends Generic<?>> generic = (Class<? extends
> Generic<?>>) Generic.class;
>      }
> }
>
> javac:
> Casting.java:4: error: inconvertible types
>                  Class<? extends Generic<?>> generic = (Class<? extends
> Generic<?>>) Generic.class;
>



More information about the compiler-dev mailing list