title: Using TypeReference with Jackson
body: <p>The following test fails with </p>
  
  <pre><code>java.util.LinkedHashMap cannot be cast to org.dabd.mapping2.MapperImplNGTest$Foo
  java.lang.ClassCastException
      at org.dabd.mapping2.MapperImplNGTest.testFromMap(MapperImplNGTest.java:82)
  </code></pre>
  
  <p>The only solution I could find is to change the fromMap signature to <code>T fromMap(S map, Class&lt;T&gt; clazz)</code> but I don't think it is necessary to pass the class explicitly.  Isn't the TypeReference enough information to instantiate the type T?  Thanks.</p>
  
  <pre><code>import java.util.Map;
  
  public interface Mapper&lt;T extends Object, S extends Map&lt;String, Object&gt;&gt; {
      public S toMap(T obj);
      public T fromMap(S map);
  }
  
  
  import com.fasterxml.jackson.core.type.TypeReference;
  import com.fasterxml.jackson.databind.ObjectMapper;
  import java.util.Map;
  
  public class MapperImpl&lt;T extends Object, S extends Map&lt;String, Object&gt;&gt;
          implements Mapper&lt;T, S&gt; {
  
      public S toMap(T obj) {
          ObjectMapper objectMapper = new ObjectMapper();
          Map&lt;String, Object&gt; map = objectMapper.convertValue(obj, Map.class);
          return (S) map;
      }
  
      public T fromMap(S map) {
          ObjectMapper objectMapper = new ObjectMapper();
          T obj = objectMapper.convertValue(map, new TypeReference&lt;T&gt;() {
          });
          return obj;
      }
  
  }
  </code></pre>
  
  <p>Test</p>
  
  <pre><code>import java.util.HashMap;
  import java.util.Map;
  import static org.testng.Assert.*;
  import org.testng.annotations.Test;
  
  
  public class MapperImplNGTest {
  
      public static class Foo {
  
          private String a;
  
          public String getA() {
              return a;
          }
  
          public void setA(String a) {
              this.a = a;
          }
  
      }
  
      public MapperImplNGTest() {
      }
  
      @Test
      public void testFromMap() {
  
          Map&lt;String, Object&gt; map = new HashMap&lt;String, Object&gt;();
          map.put("a", "aa");
  
          MapperImpl&lt;Foo, Map&lt;String, Object&gt;&gt; mapper = new MapperImpl&lt;Foo, Map&lt;String, Object&gt;&gt;();
          Foo foo = mapper.fromMap(map);
          assertEquals(foo.getA(), map.get("a"));
  
      }
  
  }
  </code></pre>