public static <T> T convertJsonRequestToVo(HttpServletRequest request, Class<T> voClass) throws Exception { request.setCharacterEncoding("utf-8"); String requestBody = HttpServletRequestUtil.readHttpServletRequestBody(request); Map<String, Object> requestMap = (Map<String, Object>) JSON.parse(requestBody); return convertMapToVo(requestMap, voClass); } public static <T> T convertMapToVo(Map<String, Object> map, Class<T> voClass) throws Exception { T obj = voClass.newInstance(); if (map.isEmpty()) return obj; BeanWrapper beanWrapper = new BeanWrapperImpl(obj); List<String> fieldList = Stream.of(voClass.getDeclaredFields()) .map(Field::getName) .collect(Collectors.toList()); fieldList.addAll(Stream.of(voClass.getSuperclass().getDeclaredFields()) .map(Field::getName) .collect(Collectors.toList())); for (Map.Entry<String, Object> entry : map.entrySet()) if (!StringUtils.isEmpty(String.valueOf(entry.getValue()))) if (fieldList.contains(entry.getKey())) beanWrapper.setPropertyValue(entry.getKey(), entry.getValue()); return obj; }
參考資料:
1、java反射以擷取父類屬性的值
https://blog.csdn.net/Mingyueyixi/article/details/51164061
2、 Java-Reflection反射-擷取包括父類在內的所有欄位
https://blog.csdn.net/qq_32452623/article/details/54025185