第一种方法直接根据是否是泛型获取


  1. public static Type[] getMethodReturnTypes(Method method) {
  2. List<Type> typeList = new ArrayList<>();
  3. Type type = method.getGenericReturnType(); //判断是否带有泛型
  4. if (type instanceof ParameterizedType) {
  5. typeList.add(((ParameterizedType) type).getRawType());
  6. Type[] actualTypeArguments = ((ParameterizedType) type).getActualTypeArguments();
  7. while (actualTypeArguments.length > 0) {
  8. type = actualTypeArguments[0];
  9. if (type instanceof ParameterizedType) {
  10. typeList.add(((ParameterizedType) type).getRawType());
  11. actualTypeArguments = ((ParameterizedType) type).getActualTypeArguments();
  12. } else {
  13. typeList.add(type);
  14. break;
  15. }
  16. }
  17. } else {
  18. typeList.add(type);
  19. }
  20. return typeList.toArray(new Type[]{});
  21. }

第二种方法 截取字符串 反射获取具体的类


  1. public static Type[] getMethodReturnTypes(Method method) {
  2. String generisInfo = method.toGenericString().split(" ")[1];
  3. if (!generisInfo.equals("void")) {
  4. generisInfo = generisInfo.replace(">", "");
  5. String[] arr = generisInfo.split("<");
  6. for (String s : arr) {
  7. try {
  8. Class<?> clazz = Class.forName(s);
  9. list.add(clazz);
  10. } catch (Exception ex) {
  11. throw new RuntimeException(ex);
  12. }
  13. }
  14. }
  15. return list.toArray(new Type[]{});
  16. }

字符串转换成对象 支持泛型,列表等


  1. /**
  2. * 字符串转换成对象 支持多级转换以及泛型等 比如 UCRoot<List<Hospital>> 、List<Hospital> 等
  3. * eg:
  4. *
  5. * @param jsonStr
  6. * @param types
  7. * @return
  8. */
  9. public static Object parseObject(String jsonStr, Type[] types) {
  10. if (isBlank(jsonStr) || ArrayUtils.isEmpty(types)) {
  11. return null;
  12. }
  13. if (types.length == 1) {
  14. if (jsonStr.startsWith("[{")) {
  15. return JSONObject.parseArray(jsonStr, (Class) types[0]);
  16. } else {
  17. return JSONObject.parseObject(jsonStr, types[0]);
  18. }
  19. }
  20. ParameterizedTypeImpl beforeType = null;
  21. if (types != null && types.length > 0) {
  22. for (int i = types.length - 1; i > 0; i--) {
  23. beforeType = new ParameterizedTypeImpl(new Type[]{beforeType == null ? types[i] : beforeType}, null, types[i - 1]);
  24. }
  25. }
  26. return JSONObject.parseObject(jsonStr, beforeType);
  27. }
Logo

魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。

更多推荐