Suppose you have a text file like:
my_setting = ON
some_method = METHOD_A
verbosity = DEBUG
...
That you wish to to update a corresponding object accordingly:
Setting my_setting = ON;
Method some_method = METHOD_A;
Verbosity verbosity = DEBUG;
...
Where all are different kind of enums.
I would like to have a generic way to instantiate the enum values. That is, at runtime using reflection, and without knowing the enum types of the object in advance.
I would have imagined something like this:
for (ConfigLine line : lines)
{
String[] tokens = line.string.split("=", 2);
String name = tokens[0].trim();
String value = tokens[1].trim();
try
{
Field field = this.getClass().getDeclaredField(name);
if(field.getType().isEnum())
{
// doesn't work (cannot convert String to enum)
field.set(this, value);
// invalid code (some strange generics issue)
field.set(this, Enum.valueOf(field.getType().getClass(), value));
}
else
{ /*...*/ }
}
catch //...
}
The question is: what should there be instead? Is it even possible to instantiate an unknown enum given its String representation?
Alternative solution with no casting
You may code your Enum similar tho this:
Then you may easily create Enum from String without reflection:
This solution is not originated from myself. I read it from somewhere else, but I can't recall the source.
getClass()
aftergetType()
should not be called - it returns the class of aClass
instanceClass<Enum>
, to avoid generic problems, because you already know that theClass
is anenum
You have an extra
getClass
call, and you have to cast (more specific cast per Bozho):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:
Call it like this: