title: Using Spring RestTemplate in generic method with generic parameter
body: <p>To use generic types with Spring RestTemplate we need to use <code>ParameterizedTypeReference</code> (<a href="https://stackoverflow.com/questions/13819734/unable-to-get-a-generic-responseentityt-where-t-is-a-generic-class-someclass/13820584#13820584">Unable to get a generic ResponseEntity&lt;T&gt; where T is a generic class &quot;SomeClass&lt;SomeGenericType&gt;&quot;</a>)</p>
  
  <p>Suppose I have some class</p>
  
  <pre><code>public class MyClass {
      int users[];
  
      public int[] getUsers() { return users; }
      public void setUsers(int[] users) {this.users = users;}
  }
  </code></pre>
  
  <p>And some wrapper class</p>
  
  <pre><code>public class ResponseWrapper &lt;T&gt; {
      T response;
  
      public T getResponse () { return response; }
      public void setResponse(T response) {this.response = response;}
  }
  </code></pre>
  
  <p>So if I'm trying to do something like this, all is OK.</p>
  
  <pre><code>public ResponseWrapper&lt;MyClass&gt; makeRequest(URI uri) {
      ResponseEntity&lt;ResponseWrapper&lt;MyClass&gt;&gt; response = template.exchange(
          uri,
          HttpMethod.POST,
          null,
          new ParameterizedTypeReference&lt;ResponseWrapper&lt;MyClass&gt;&gt;() {});
      return response;
  }
  </code></pre>
  
  <p>But when I'm trying to create generic variant of the above method ...</p>
  
  <pre><code>public &lt;T&gt; ResponseWrapper&lt;T&gt; makeRequest(URI uri, Class&lt;T&gt; clazz) {
     ResponseEntity&lt;ResponseWrapper&lt;T&gt;&gt; response = template.exchange(
          uri,
          HttpMethod.POST,
          null,
          new ParameterizedTypeReference&lt;ResponseWrapper&lt;T&gt;&gt;() {});
      return response;
  }
  </code></pre>
  
  <p>... and calling this method like so ...</p>
  
  <pre><code>makeRequest(uri, MyClass.class)
  </code></pre>
  
  <p>... instead of getting <code>ResponseEntity&lt;ResponseWrapper&lt;MyClass&gt;&gt;</code> object I'm getting <code>ResponseEntity&lt;ResponseWrapper&lt;LinkedHashSet&gt;&gt;</code> object. </p>
  
  <p>How can I solve this problem? Is it a RestTemplate bug?</p>
  
  <p><strong>UPDATE 1</strong>
  Thanks to @Sotirios I understand the concept. Unfortunately I'm newly registered here so I cant comment on his answer, so writing it here. Im not sure that I clearly understand how to implement the proposed approach to solve my problem with <code>Map</code> with <code>Class</code> key (Proposed by @Sotirios in the end of his answer). Would someone mind to give an example?</p>