使用TypeTools解析泛型类型信息

时间:2014-10-06 18:13:04

标签: java generics type-resolution

在下面的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;
    }

1 个答案:

答案 0 :(得分:0)

TypeTools或Java中的任何泛型类型解析始终要求在类型定义中捕获类型参数。只要MapperImpl被子类化,您尝试做的就会正常工作,以便在类型定义中捕获TS的值。例如:

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