在下面的fromMap的实现中,我想使用T
获取泛型类型TypeTools
的运行时类型,但我在NullPointerException
中遇到了TypeResolver.resolveRawArguments(MapperImpl.class, getClass());
。
我怎样才能做到这一点?
Mapper.java:
import java.util.Map;
public interface Mapper<T extends Object, S extends Map<String, Object>> {
public S toMap(T obj);
public T fromMap(S map);
}
MapperImpl.java
import com.fasterxml.jackson.databind.ObjectMapper;
import java.util.Map;
import net.jodah.typetools.TypeResolver;
public class MapperImpl<T extends Object, S extends Map<String, Object>>
implements Mapper<T, S> {
public S toMap(T obj) {
ObjectMapper objectMapper = new ObjectMapper();
Map<String, Object> map = objectMapper.convertValue(obj, Map.class);
return (S) map;
}
public T fromMap(S map) {
ObjectMapper objectMapper = new ObjectMapper();
Class<?>[] ts = TypeResolver.resolveRawArguments(MapperImpl.class, getClass());
Class<T> classT = (Class<T>) ts[0];
T obj = objectMapper.convertValue(map, classT);
return obj;
}
答案 0 :(得分:0)
TypeTools或Java中的任何泛型类型解析始终要求在类型定义中捕获类型参数。只要MapperImpl被子类化,您尝试做的就会正常工作,以便在类型定义中捕获T
和S
的值。例如:
public class FooMapper extends MapperImpl<Foo, ArrayList<String, Object>> {}