[java反射]将对象Object转换为Map

下面运用java反射的知识,写一个工具方法,用来将对象Object转换为Map,

转换规则为:Map中的key是原对象的属性名,value是原来对象的属性值

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;

public class ReflectUtil {
    /**
     *
     * @Title: objectToMap
     * @Description: 将object转换为map,默认不保留空值
     * @param @param obj
     * @return Map<String,Object> 返回类型
     * @throws
     */
    public static Map objectToMap(Object obj) {

        Map<String, Object> map = new HashMap<String, Object>();
        map = objectToMap(obj, false);
        return map;
    }

    public static Map objectToMap(Object obj, boolean keepNullVal) {
        if (obj == null) {
            return null;
        }

        Map<String, Object> map = new HashMap<String, Object>();
        try {
            Field[] declaredFields = obj.getClass().getDeclaredFields();
            for (Field field : declaredFields) {
                field.setAccessible(true);
                if (keepNullVal == true) {
                    map.put(field.getName(), field.get(obj));
                } else {
                    if (field.get(obj) != null && !"".equals(field.get(obj).toString())) {
                        map.put(field.getName(), field.get(obj));
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return map;
    }
}

猜你喜欢

转载自blog.csdn.net/u010999809/article/details/79939018