使用TypeTools解决泛型类型信息 [英] Resolving generic type information with TypeTools

查看:108
本文介绍了使用TypeTools解决泛型类型信息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在下面的fromMap的实现中,我想使用 TypeTools 获得通用类型 T 的运行时类型,但是我遇到了 NullPointerException TypeResolver.resolveRawArguments(MapperImpl.class,getClass()); 中的code>.

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());.

我该如何实现?

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或Java中的任何通用类型解析,始终要求在类型定义中捕获类型实参.只要将MapperImpl子类化,以便在类型定义中捕获 T S 的值,您尝试执行的操作就可以正常工作.例如:

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

这篇关于使用TypeTools解决泛型类型信息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆