Resolving generic type information with TypeTools

霸气de小男生 提交于 2019-12-12 04:45:38

问题


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;
    }

回答1:


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 and S are captured in a type definition. Ex:

public class FooMapper extends MapperImpl<Foo, ArrayList<String, Object>> {}


来源:https://stackoverflow.com/questions/26222214/resolving-generic-type-information-with-typetools

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!