Java 通常会在编译时删除 Generics
数据,但有可能获得该信息(Jackson ObjectMapper
做得很好)。
我的问题:我有一个具有 List 属性的类:
public class User {
public List<Long> listProp;//it is public only to keep the example simple
}
如何获得正确的 TypeReference
(或 JavaType
?),以便我可以通过编程方式将 JSON 字符串映射到正确的列表类型,具有 的实例code>Class
类(User.class)和属性名(listProp)?我的意思是:
TypeReference typeReference = ...;//how to get the typeReference?
List<Long> correctList = om.readValue(jsonEntry.getValue(), typeReference);//this should return a List<Long> and not eg. a List<Integer>
最佳答案
您是否尝试过映射器的 constructType 方法?
Type genericType = User.class.getField("listProp").getGenericType();
List<Long> correctList = om.readValue(jsonEntry.getValue(), om.constructType(genericType));
关于java - 如何获取 Jackson ObjectMapper 的通用类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17568497/