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

[1645 byte] By [kevin.mcguinnessa] at [2007-11-27 11:13:02]
# 1

Why do you need this? Object.getClass() returns a Class<T> of the actual object already.

ejpa at 2007-7-29 13:58:21 > top of Java-index,Core,Core APIs...
# 2

> Why do you need this? Object.getClass() returns a

> Class<T> of the actual object already.

Only if you know the type. Generic types return Class<?>

so the cast is necessary

kevin.mcguinnessa at 2007-7-29 13:58:21 > top of Java-index,Core,Core APIs...
# 3

> Hi, I was wondering if it is save to surpress the

> unchecked warning in this code:

>

> > public static <U extends Enum><U>> Class<U> classOf(U

> val) {

>return (Class<U>) val.getClass();

>

I cannot think of any situation, where this should break.

getClass(), btw., never returns Class<U> but a bounded wildcard, if it knows about the bound (here, it should return Class<? extends Enum>).

stefan.schulza at 2007-7-29 13:58:21 > top of Java-index,Core,Core APIs...