title: Conveniently map between enum and int / String
body: <p>When working with variables/parameters that can only take a finite number of values, I try to always use Java's <code>enum</code>, as in </p>
  
  <pre><code>public enum BonusType {
    MONTHLY, YEARLY, ONE_OFF
  }
  </code></pre>
  
  <p>As long as I stay inside my code, that works fine. However, I often need to interface with other code that uses plain <code>int</code> (or <code>String</code>) values for the same purpose, or I need to read/write from/to a database where the data is stored as a number or string.</p>
  
  <p>In that case, I'd like to have a convenient way to associate each enum value with a an integer, such that I can convert both ways (in other words, I need a "reversible enum").</p>
  
  <p>Going from enum to int is easy:</p>
  
  <pre><code>public enum BonusType {
    public final int id;
  
    BonusType(int id) {
      this.id = id;
    }
    MONTHLY(1), YEARLY(2), ONE_OFF(3);
  }
  </code></pre>
  
  <p>Then I can access the int value as <code>BonusType x = MONTHLY; int id = x.id;</code>.</p>
  
  <p>However, I can see no nice way for the reverse, i.e. going from int to enum. Ideally, something like</p>
  
  <pre><code>BonusType bt = BonusType.getById(2); 
  </code></pre>
  
  <p>The only solutions I could come up with are:</p>
  
  <ul>
  <li>Put a lookup method into the enum, which uses <code>BonusType.values()</code> to fill a map "int -> enum", then caches that and uses it for lookups. Would work, but I'd have to copy this method identically into each enum I use :-(.</li>
  <li>Put the lookup method into a static utility class. Then I'd only need one "lookup" method, but I'd have to fiddle with reflection to get it to work for an arbitrary enum.</li>
  </ul>
  
  <p>Both methods seem terribly awkward for such a simple (?) problem. </p>
  
  <p>Any other ideas/insights?</p>