raw types warnings and instanceof

Maurizio Cimadamore Maurizio.Cimadamore at Sun.COM
Mon Nov 3 03:17:56 PST 2008

FYI here's the warning I found when cleaning up langtools; as I said 
there are only two warnings that cannot be fixed - both of the same 
kind; both warnings are generated by the following code pattern:

Class<?> token;
Object value = Enum.valueOf((Class)token, "");

Since Enum.valueof is a generic method declaring an fbound (<T extends 
Enum<T>>) , it's not possible to find an instantiation for the 
type-parameter T without going through an unchecked method call. In 
fact, all possible kinds of checked call will result in a compile-time 
error. The only way to remove this warning is to have some type that 
could be used for parameterizing  the 'Class' in the cast.

Class<?> token;
Object value = Enum.valueOf((Class<T>)token, '');

The problem is that, obviously, we don't always have such a T so that 
this warning could be unavoidable.

Rémi Forax wrote:
> Martin Buchholz a écrit :
>> Here's another case where raw type warnings seem
>> well-intentioned, but going too far.
>>  $ cat ClassRaw.java; jver coll jr ClassRaw
>> public class ClassRaw {
>>     public static void main(String[] args) throws Throwable {
>>         Class<Comparable> x = Comparable.class;
>>     }
>> }
>> ==> javac -Xlint:all ClassRaw.java
>> ClassRaw.java:3: warning: [raw-type] found raw type: 
>> java.lang.Comparable
>> missing type parameters for generic class java.lang.Comparable<T>
>>         Class<Comparable> x = Comparable.class;
>>               ^
>> 1 warning
>> My first impression is that these warnings are more verbose,
>> more annoying, and less likely to find bugs than even "unchecked",
>> and that even pedants like myself will change their scripts to do
>> -Xlint:all,-rawtypes instead of -Xlint:all
>> Martin
> The problem with  Class<Comparable> is that it's a rare type, a mix 
> between parameterized type
> and raw type and you clearly want to detect them, by example a use of 
> List<List>> should raise a warning.
> In my opinion, there is two way to solve the problem:
> 1) change the JLS to use wildcard instead of raw type in getClass() 
> and .class,
>     this require to add an unsafe conversion between a rare type and 
> its equivalent using a wildcard
>     to avoid to emit an error in code that compile with prevous version.
> 2) Have a special rule for Class<>, i.e allow Class of a raw type 
> without emitting any warning.
> Rémi

More information about the compiler-dev mailing list