title: Use Java generics to accept and Interface and return a Class that implements that Interface
body: <p>I'm writing a Class to centralise my EJB lookups. As such, I pass in an Interface to a method and use that as the basis for the EJB lookup and then return an instance of the appropriate Class.</p>
  
  <p>I want to use Generics so that I don't have to cast the result when calling the method.</p>
  
  <p>I have written the below, which works, but I have a bad feeling about it and I'm pretty sure it's not actually doing what I want.</p>
  
  <p>public class EJBProvider {</p>
  
  <pre><code>    public static &lt;T&gt; T lookupEjb(Class theClass) {
          try {
              InitialContext ic = new InitialContext();
  
              String simpleName = String.format("java:comp/env/ejb/%s", theClass.getSimpleName());
              final T ejb = (T)ic.lookup(simpleName);
              return ejb;
          } catch (Exception e) {
              e.printStackTrace();
              return null;
          }
      }
  }
  
  
  private MyEjbLocal myEjb = EJBProvider.lookupEjb(MyEjbLocal.class);
  </code></pre>