Given this code:
List<Integer> ints = new ArrayList<Integer>();
// Type mismatch:
// cannot convert from Class<capture#1-of ? extends List> to Class<List<Integer>>
Class<List<Integer>> typeTry1 = ints.getClass();
// Type safety:
// Unchecked cast from Class<capture#2-of ? extends List> to Class<List<Integer>>
Class<List<Integer>> typeTry2 = (Class<List<Integer>>) ints.getClass();
// List is a raw type. References to generic type List<E> should be parameterized
Class<? extends List> typeTry3 = ints.getClass();
Is there a way to get the Class of a List<Integer> without an error or warning? I can suppress the warnings easily enough, but if Java requires me to suppress a warning for this valid code, I am very disappoint.
On the other hand, if warning suppression is the only way, what is the safest to suppress?
This is a real Catch-22 in Java.
The compiler warns you if you don’t add a generic type to
List:That’s because, in most cases, it’s really best to type your Lists.
However, because of type erasure, there’s no way for Java to figure out the generic type of
Listat runtime, and the compiler knows that. Therefore, there is no method onClassthat will returned a typed object:So you must cast it to a typed list. However, as you know, since there is no runtime type checking, Java warns you about any casts to a typed variable:
Any attempt to get around this is essentially a means of confusing the compiler, and will inevitably be convoluted.
Your best bet then is to go with Option B:
The safest way to suppress this warning is to make your
@SuppressWarnings("unchecked")annotation as localized as possible. Put them above each individual unchecked cast. That way it’s absolutely clear who’s causing the warning.