In the implementation of fromMap below I would like to get the runtime type of the generic type T
using TypeTools
but I am stuck with a NullPointerException
in TypeResolver.resolveRawArguments(MapperImpl.class, getClass());
.
How can I achieve this?
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;
}
TypeTools, or any generic type resolution in Java, always required that the type arguments be captured in a type definition. What you're attempting to do will work fine so long as MapperImpl is subclassed so that the value of
T
andS
are captured in a type definition. Ex: