通过反射将java对象转Map对象(包含继承父类)

/**
         * 将Object对象里面的属性和值转化成Map对象
         *
         * @param obj
         * @return
         * @throws IllegalAccessException
         */
        public static Map<String, Object> objectToMap(Object obj) throws IllegalAccessException {
            Map<String, Object> map = new HashMap<String,Object>();
            Class<?> clazz = obj.getClass();
            List<Field> fields = new ArrayList<>();
            //把父类包含的字段遍历出来
            while (clazz!=null){
                fields.addAll(Arrays.asList(clazz.getDeclaredFields()));
                clazz = clazz.getSuperclass();

            }
            for (Field field : fields) {
                field.setAccessible(true);
                String fieldName = field.getName();
                Object value = field.get(obj);
                map.put(fieldName, value);
            }
            return map;
        }

 

posted @ 2020-07-08 17:24  听风的dog  阅读(1181)  评论(1编辑  收藏  举报