title: Returning Object with type arguments using generics and avoiding Type Safety warnings
body: <p>I am writing a class that supplies some common utilities for my environment.</p>
  
  <p>In this class, I have the following method that receives a JSON String, and is supposed to map the JSON to an appropriate Object:</p>
  
  <pre><code>public static &lt;T&gt; T mapJsonToObject(String json, Class&lt;T&gt; clazz) {
      ObjectMapper mapper = new ObjectMapper();
      T parsedObject = null;
      try {
          parsedObject = mapper.readValue(json, clazz);
      } catch (Exception e) {
          e.printStackTrace();
      }
      return parsedObject;
  }
  </code></pre>
  
  <p>The actual conversion from String to the appropriate class is done using the <a href="https://github.com/FasterXML/jackson" rel="noreferrer">Jackson</a> library, and is working properly, as well as this entire method.</p>
  
  <p>Calls to this method such as:</p>
  
  <pre><code>Object o = MyUtilities.mapJsonToObject(jsonString, Object.class);
  Point p = MyUtilities.mapJsonToObject(jsonString, Point.class);
  PhoneBook pb = MyUtilities.mapJsonToObject(jsonString, PhoneBook.class);
  </code></pre>
  
  <p>are all working properly.</p>
  
  <p>However, if I don't want to map the JSON to a specific Object, and I just want to convert it to a map using key/value pairs, like so:</p>
  
  <pre><code>HashMap&lt;String, Object&gt; myMap = MyUtilities.mapJsonToObject(result, HashMap.class);
  </code></pre>
  
  <p>I get a <code>"Type safety: The expression of type HashMap needs unchecked conversion to conform to HashMap&lt;String,Object&gt;"</code> warning from the compiler. This is due to the fact that I'm losing the generic arguments when using HashMap.class</p>
  
  <p>While writing this question I actually stumbled upon <a href="http://www.javacodegeeks.com/2013/01/json-deserialization-with-jackson-and-super-type-tokens.html" rel="noreferrer">this</a> tutorial and thought of overloading the mapping method in the following way:</p>
  
  <pre><code>public static &lt;T&gt; T mapJsonToObject(String json, T obj) {
      ObjectMapper mapper = new ObjectMapper();
      T parsedObject = null;
      try {
          parsedObject = mapper.readValue(json, new TypeReference&lt;T&gt;() {});
      } catch (Exception e) {
              e.printStackTrace();            
      }
      return parsedObject;
  }
  </code></pre>
  
  <p>This requires the passing of an actual Object which I prefer to avoid:</p>
  
  <pre><code>HashMap&lt;String, Object&gt; myMap = null;
  myMap = MyUtilities.mapJsonToObject(result, myMap);
  </code></pre>
  
  <p>Any idea how to improve these two methods to avoid both the passing of an Object, and the type safety warning? Please note that I'm not looking for a solution specific to HashMap</p>