title: Java generic function: how to return Generic type
body: <p>Here's a Java generic pattern:</p>
  
  <pre><code>public &lt;T&gt; T getResultData(Class&lt;T&gt; resultClass, other_args) { 
     ...
     return resultClass.cast(T-thing);
  }
  </code></pre>
  
  <p>A typical call looks like:</p>
  
  <pre><code>   DoubleBuffer buffer;
     buffer = thing.getResultData(DoubleBuffer.class, args);
  </code></pre>
  
  <p>I've never been able to figure out how to use this pattern cleanly when the desired return type is, itself, generic. To be 'concrete', what if a function like this wants to return <code>Map&lt;String,String&gt;</code>? Since you can't get a class object for a generic, of course, the only option would be to pass <code>Map.class</code>, and then you need a cast and an <code>@SuppressWarning</code> after all.</p>
  
  <p>One ends up with a call like:</p>
  
  <pre><code>Map&lt;String, String&gt; returnedMap;
  returnedMap = thing.getResultData(Map.class, some_other_args);
  </code></pre>
  
  <p>Now one is back to needing casts and suppressing a warning.</p>
  
  <p>I suppose that one could take something from the <code>java.lang.reflect.Type</code> family instead of the <code>Class</code>, but those aren't especially easy to concoct. That looks like:</p>
  
  <pre><code>class Dummy {
   Map&lt;String, String&gt; field;
  }
  
  ...
  
  Type typeObject = Dummy.class.getField("field").getGenericType();
  </code></pre>
  
  <p>Given this, the called function could extract the base type and use that for casting or newInstance-ing, but the dummy field business sure looks ugly.</p>
  
  <p>Note that functions like this are not always calling <code>newInstance</code>. Obviously, if they do, they don't need to call <code>resultClass.cast</code>.</p>