Type safety with getting the class of an enum
Hi, I was wondering if it is save to surpress the unchecked warning in this code:
publicstatic <Uextends Enum><U>> Class<U> classOf(U val){
return (Class<U>) val.getClass();
}
My reasoning is that since enums cannot be subclassed, val.getClass() will always be of type Class<U>. If it's not safe, than what is the safe way to do it? Here is a simplified example of the problem I have:
class EnumOption<Textends Enum><T>>{
private T defaultValue;
private Class<T> clazz;
EnumOption(T value){
// unchecked warning
clazz = (Class<T>) value.getClass();
defaultValue = value
}
T convert(String s){
return Enum.valueOf(clazz, value.toString());
}
}
My current solution is to also take the class as an argument, as follows:
EnumOption(Class<T> c, T v){
clazz = c;
defaultValue = v;
}
But I'd rather just surpress the exception and avoid the extra parameter if it's safe.
-Kevin

