在尝试使用TypeTools Resolving generic type information with TypeTools后,我试图用https://github.com/cowtowncoder/java-classmate代替。使用java同学解决泛型类型
有人可以帮我修复这段代码吗?
public T fromMap(S map) {
TypeResolver typeResolver = new TypeResolver();
ResolvedType type = typeResolver.resolve((new MapperImpl<T, S>() {}).getClass());
List<ResolvedType> params = type.typeParametersFor(MapperImpl.class);
ResolvedType typeT = params.get(0);
ObjectMapper objectMapper = new ObjectMapper();
T obj = objectMapper.convertValue(map, (Class<T>) typeT.getErasedType());
return obj;
}
我收到此错误:
java.util.LinkedHashMap cannot be cast to LoginInputMapTest$Foo java.lang.ClassCastException at shouldMapToFoo(LoginInputMapTest.java:83)
这个最小的测试案例:
public static class Foo {
private String a;
public String getA() {
return a;
}
public void setA(String a) {
this.a = a;
}
}
@Test
public void shouldMapToFoo() {
Map<String, Object> map = new HashMap<>();
map.put("a", "aaa");
Mapper<Foo, Map<String, Object>> mapper = new MapperImpl<>();
Foo foo = mapper.fromMap(map);
Assert.assertEquals(foo.getA(), map.get("a"));
}
你的MapperImpl做些什么吗?看起来你创建了一个匿名类而没有实际访问它。或者这只是一个缩写? – 2014-10-07 14:58:59
匿名类在那里提供一个子类型。我认为你需要它来解决泛型类型。看到这个例子:https://github.com/cowtowncoder/java-classmate#resolving-type-parameters-for-a-class – dmz73 2014-10-07 15:04:07