I'm trying to generify old code, and there is some code where, given something like Integer.class
, it returns Integer.TYPE
(and vice-versa), and so on for the rest of the wrappers (if the input is not a wrapper, it returns the input class). This seems like a candidate for conversion (if it doesn't already exist somewhere). So, I have something like this:
public static <T> Class<T> convert(Class<T> type) {
if (type == Integer.class) return Integer.TYPE;
// and so on
return type;
}
The problem with this code is that the compiler does not, by itself, know that in the if block we have ascertained that T == Integer
, and thus does not know that returning Integer.TYPE
is OK, thus barfing. Of course, we can always explicitly cast to Class<T>
. The question is, is this cast safe, and thus I can be comfortable in adding the @SuppressWarnings("unchecked")
annotation?
@SuppressWarnings("unchecked")
should be fine here: we know each wrapper class W
declares its TYPE
field as a Class<W>
, - probably just add a comment to explain that rational.
Note that Guava already has Primitives.unwrap
to handle this for you, in case you're using it.