title: Implement generic return type for methods in Java
body: <p>Hello  I have few model return types and a rest call that can have any one of those return type. I want to implement generics or something like that which enables to return the expected type model. For example:</p>
  <p>Conside I have 2 models ItemDetails.java and ItemDetailsWithTimestamp.java
  In one case i need to return the first model and in another case i want the second one:
  I tried something like:</p>
  <p><strong><code>Test.java</code></strong></p>
  <pre class="lang-java prettyprint-override"><code>@Test
  public void getitemTest() {
      ItemApi itemApi = new ItemApi();
      ItemDetails result = itemApi.getitem(ItemDetails.class);
  } 
      
  public void getitemWithTimestampTest() {
      ItemApi itemApi = new ItemApi();
      ItemDetailsWithTimestamp result = itemApi.getitem(ItemDetailsWithTimestamp.class);
  } 
  </code></pre>
  <p>And in the <strong><code>ItemApi</code></strong> class the method <code>getitem</code>:</p>
  <pre class="lang-java prettyprint-override"><code>public static &lt;T&gt; ResponseEntity&lt;T&gt; getitem(Class&lt;T&gt; type) {
      #somecode for implementing rest calls
      return (ResponseEntity&lt;T&gt;) response;
  }
  </code></pre>
  <p>Note: This is not the full code as seen but the extract which is perhaps enough to explain the problem. The above code returns an error on running the test:</p>
  <p>java.lang.ClassCastException: class java.util.LinkedHashMap cannot be cast to class myproject.model.ItemDetails (java.util.LinkedHashMap is in module java.base of loader 'bootstrap'; myproject.model.ItemDetails is in unnamed module of loader 'app')</p>
  <p>What could be the issues, is it not possible to accommodate different types using this approach or do i miss something. Thanks in advance,</p>