It's actually kind of a pain because of the way Enum
is declared. You wouldn't be able to call valueOf
with a Class<?>
(nor e.g. a Class<? extends Enum<?>>
). The only way to do it without unchecked casting is to go through getEnumConstants
:
public boolean tryCast(String value){
for(Object o : enumClass.getEnumConstants()) {
Enum<?> e = (Enum<?>) o;
if(e.name().equals(value))
return true;
}
return false;
}
If you don't care about the unchecked cast you can do:
try {
Enum.valueOf( (Class) enumClass, value );
return true;
} catch(IllegalArgumentException e) {
return false;
}
But, you know, some people will grumble because it's a raw type. getEnumConstants
is probably better anyways since then you don't use exceptions for this kind of thing.
In addition, since you have a Class<?>
you might want to perform a check like
if( !Enum.class.isAssignableFrom(enumClass) )
return false;
or throw an exception in the constructor.