title: Implement converters for entities with Java Generics
body: <p>I'm working on JSF project with Spring and Hibernate which among other things has a number of <code>Converter</code>s that follow the same pattern: </p>
  
  <ul>
  <li><p><code>getAsObject</code> receives the string representation of the object id, converts it to a number, and fetch the entity of the given kind and the given id</p></li>
  <li><p><code>getAsString</code> receives and entity and returns the id of the object converted to <code>String</code></p></li>
  </ul>
  
  <p>The code is essentially what follows (checks omitted):</p>
  
  <pre><code>@ManagedBean(name="myConverter")
  @SessionScoped
  public class MyConverter implements Converter {
      private MyService myService;
  
      /* ... */
      @Override
      public Object getAsObject(FacesContext facesContext, UIComponent uiComponent, String value) {
          int id = Integer.parseInt(value);
          return myService.getById(id);
      }
  
      @Override
      public String getAsString(FacesContext facesContext, UIComponent uiComponent, Object value) {
          return ((MyEntity)value).getId().toString();
      }
  }
  </code></pre>
  
  <p>Given the large number of <code>Converter</code>s that are exactly like this (except for the type of <code>MyService</code> and <code>MyEntity</code> of course), I was wondering if it was worth using a single generic converter. 
  The implementation of the generic by itself is not difficult, but I'm not sure about the right approach to declare the Beans.</p>
  
  <p>A possible solution is the following:</p>
  
  <p>1 - Write the generic implementation, let's call it <code>MyGenericConverter</code>, without any Bean annotation</p>
  
  <p>2 - Write the specific converter ad a subclass of <code>MyGenericConverter&lt;T&gt;</code> and annotate it as needed:</p>
  
  <pre><code>@ManagedBean(name="myFooConverter")
  @SessionScoped
  public class MyFooConverter implements MyGenericConverter&lt;Foo&gt; {
      /* ... */
  }
  </code></pre>
  
  <p>While writing this I realized that maybe a Generic is not really needed, so maybe I could simply write a base class with the implementation of the two methods, and subclass as needed.</p>
  
  <p>There a few non trivial details that have to be taken care of (like the fact that I'd have to abstract the <code>MyService</code> class in some way) so my first question is : is it worth the hassle ?</p>
  
  <p>And if so, are there other approaches ? </p>