在尝试使用 TypeTools Resolving generic type information with TypeTools 失败后,我尝试改用https://github.com/cowtowncoder/java-classmate。
有人可以帮我修复此代码吗?
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 不能在 shouldMapToFoo(LoginInputMapTest.java:83) 处转换为 LoginInputMapTest$Foo java.lang.ClassCastException
使用这个最小的测试用例:
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"));
}