#先上代码
/**
* 解析泛型类型
* @param type
* @return
*/
public static List<Class<?>> parseGenericType(Type type){
List<Class<?>> rootList = new ArrayList<Class<?>>();
if(type instanceof ParameterizedType){
ParameterizedType pType = (ParameterizedType)type;
rootList.add((Class<?>)pType.getRawType());
for(Type at : pType.getActualTypeArguments()){
List<Class<?>> childList = parseGenericType(at);
rootList.addAll(childList);
}
}else{
rootList.add((Class<?>)type);
}
return rootList;
}
public static JavaType parseJavaType(ObjectMapper jsonMapper, Type genericParameterType){
List<Class<?>> list = parseGenericType(genericParameterType);
if(list==null || list.size()==1){
return jsonMapper.getTypeFactory().constructType(genericParameterType);
}
Class<?>[] classes = list.toArray(new Class[list.size()]);
Class<?>[] paramClasses = new Class[classes.length-1];
System.arraycopy(classes,1,paramClasses,0,paramClasses.length);
JavaType javaType = jsonMapper.getTypeFactory().constructParametrizedType(classes[0],classes[0],paramClasses);
return javaType;
}
#使用例子
JavaType javaType = parseJavaType(objectMapper,method.getGenericReturnType());
MyBean bean = objectMapper.readValue(jsonStr, javaType);