Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: instantiating an enum using reflection

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?

like image 737
dagnelies Avatar asked Sep 17 '10 13:09

dagnelies


People also ask

Can you instantiate an enum Java?

You do not instantiate an enum , but rely the constants defined. Enums can be used in a switch-case statement, just like an int .

Can you instantiate an enum class?

No, you cannot instantiate enums, and there's a good reason for that. Enums are for when you have a fixed set of related constants. You don't want to instantiate one, because then the set would not be fixed.

What is Java reflection?

Reflection is a feature in the Java programming language. It allows an executing Java program to examine or "introspect" upon itself, and manipulate internal properties of the program. For example, it's possible for a Java class to obtain the names of all its members and display them.

Can we instantiate an enum type using the new operator?

We cannot instantiate an enum type using the new operator. An enum type is implicitly final. Enum types inherit members from the Object class, as any other reference type.


2 Answers

field.set(this, Enum.valueOf((Class<Enum>) field.getType(), value)); 
  • getClass() after getType() should not be called - it returns the class of a Class instance
  • You can cast Class<Enum>, to avoid generic problems, because you already know that the Class is an enum
like image 86
Bozho Avatar answered Sep 21 '22 13:09

Bozho


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 } 
like image 30
Rebzie Avatar answered Sep 18 '22 13:09

Rebzie