对象转换成Map

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/dc282614966/article/details/83542376
 public static Map<String, Object> beanToMap(Object requestBody, String[] excludeField) {
        if (requestBody == null) {
            return null;
        }
        List<Field> fields = new ArrayList<>();

        // 当父类为null的时候说明到达了最上层的父类(Object类)
        Class tempClass = requestBody.getClass();
        while (tempClass != null) {
            fields.addAll(Arrays.asList(tempClass.getDeclaredFields()));
            // 得到父类,然后赋给自己
            tempClass = tempClass.getSuperclass();
        }
        /*=====迭代属性排序=====*/
        Map<String, Object> fieldMap = new TreeMap<>();
        for (Field field : fields) {
            String name = field.getName();
            if (excludeField != null && Arrays.asList(excludeField).contains(name)) {
                System.out.println("剔除属性:"+name);
                continue;
            }
            field.setAccessible(true);
            Object value = null;
            try {
                value = field.get(requestBody);
            } catch (IllegalAccessException e) {
                System.out.println("反射获取对象属性值异常:"+e);
            }
            if (StringUtils.isNotBlank((String) value)) {
                fieldMap.put(name, value.toString());
            }
        }
        return fieldMap;
    }

猜你喜欢

转载自blog.csdn.net/dc282614966/article/details/83542376