Java 通过反射获取父类字段的方法

    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


猜你喜欢

转载自blog.csdn.net/HeatDeath/article/details/80067207