第一种方法直接根据是否是泛型获取
public static Type[] getMethodReturnTypes(Method method) {
List<Type> typeList = new ArrayList<>();
Type type = method.getGenericReturnType(); //判断是否带有泛型
if (type instanceof ParameterizedType) {
typeList.add(((ParameterizedType) type).getRawType());
Type[] actualTypeArguments = ((ParameterizedType) type).getActualTypeArguments();
while (actualTypeArguments.length > 0) {
type = actualTypeArguments[0];
if (type instanceof ParameterizedType) {
typeList.add(((ParameterizedType) type).getRawType());
actualTypeArguments = ((ParameterizedType) type).getActualTypeArguments();
} else {
typeList.add(type);
break;
}
}
} else {
typeList.add(type);
}
return typeList.toArray(new Type[]{});
}
第二种方法 截取字符串 反射获取具体的类
public static Type[] getMethodReturnTypes(Method method) {
String generisInfo = method.toGenericString().split(" ")[1];
if (!generisInfo.equals("void")) {
generisInfo = generisInfo.replace(">", "");
String[] arr = generisInfo.split("<");
for (String s : arr) {
try {
Class<?> clazz = Class.forName(s);
list.add(clazz);
} catch (Exception ex) {
throw new RuntimeException(ex);
}
}
}
return list.toArray(new Type[]{});
}
字符串转换成对象 支持泛型,列表等
/**
* 字符串转换成对象 支持多级转换以及泛型等 比如 UCRoot<List<Hospital>> 、List<Hospital> 等
* eg:
*
* @param jsonStr
* @param types
* @return
*/
public static Object parseObject(String jsonStr, Type[] types) {
if (isBlank(jsonStr) || ArrayUtils.isEmpty(types)) {
return null;
}
if (types.length == 1) {
if (jsonStr.startsWith("[{")) {
return JSONObject.parseArray(jsonStr, (Class) types[0]);
} else {
return JSONObject.parseObject(jsonStr, types[0]);
}
}
ParameterizedTypeImpl beforeType = null;
if (types != null && types.length > 0) {
for (int i = types.length - 1; i > 0; i--) {
beforeType = new ParameterizedTypeImpl(new Type[]{beforeType == null ? types[i] : beforeType}, null, types[i - 1]);
}
}
return JSONObject.parseObject(jsonStr, beforeType);
}