解决与TypeTools泛型类型信息(Resolving generic type informat

2019-11-03 09:09发布

在fromMap执行下面我想获得泛型类型的运行时类型T使用TypeTools但我坚持一个NullPointerExceptionTypeResolver.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;
    }

Answer 1:

TypeTools,或在Java中的任何泛型类型的分辨率,总是需要的类型参数的类型定义被捕获。 你试图做会正常工作,只要MapperImpl的子类,这样的价值是什么TS的类型定义被捕获。 例如:

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


文章来源: Resolving generic type information with TypeTools