title: Java: instantiating an enum using reflection
body: <p>Suppose you have a text file like:</p>
  
  <pre><code>my_setting = ON
  some_method = METHOD_A
  verbosity = DEBUG
  ...
  </code></pre>
  
  <p>That you wish to to update a corresponding object accordingly:</p>
  
  <pre><code>Setting my_setting = ON;
  Method some_method = METHOD_A;
  Verbosity verbosity = DEBUG;
  ...
  </code></pre>
  
  <p>Where all are different kind of enums.</p>
  
  <p>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.</p>
  
  <p>I would have imagined something like this:</p>
  
  <pre><code>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 //...
  }
  </code></pre>
  
  <p>The question is: what should there be instead? Is it even possible to instantiate an unknown enum given its String representation?</p>