Java: instantiating an enum using reflection
Solution 1:
field.set(this, Enum.valueOf((Class<Enum>) field.getType(), value));
-
getClass()
aftergetType()
should not be called - it returns the class of aClass
instance - You can cast
Class<Enum>
, to avoid generic problems, because you already know that theClass
is anenum
Solution 2:
Alternative solution with no casting
try {
Method valueOf = field.getType().getMethod("valueOf", String.class);
Object value = valueOf.invoke(null, param);
field.set(test, value);
} catch ( ReflectiveOperationException e) {
// handle error here
}
Solution 3:
You have an extra getClass
call, and you have to cast (more specific cast per Bozho):
field.set(test, Enum.valueOf((Class<Enum>) field.getType(), value));
Solution 4:
The accepted answer results in warnings because it uses the raw type Enum instead of Enum<T extends Enum<T>>.
To get around this you need to use a generic method like this:
@SuppressWarnings("unchecked")
private <T extends Enum<T>> T createEnumInstance(String name, Type type) {
return Enum.valueOf((Class<T>) type, name);
}
Call it like this:
Enum<?> enum = createEnumInstance(name, field.getType());
field.set(this, enum);