java 根据method获取方法的返回值类型
第一种方法直接根据是否是泛型获取public static Type[] getMethodReturnTypes(Method method) {List<Type> typeList = new ArrayList<>();Type type = method.getGenericReturnType(); //判断是否带有泛型if (type instanceof P
·
第一种方法直接根据是否是泛型获取
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);}
魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。
更多推荐

所有评论(0)