Java对象转换成Map

需求总是千奇百怪,对象转成map,看似没必要,但就是有这个需求,所以记录下来

首先是Bean

package tools;

import lombok.Data;

/**
 * 车辆实体类
 */
@Data
public class Car {

    private String id;
    private String model;//型号
    private String color;//颜色
    private String volume;//排量
    private int year;//年份
}

然后是主要方法和测试类

package tools;

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

public class MapTools {

    public static void main(String[] args) throws Exception{
        Car car = new Car();
        car.setId("00000");
        car.setColor("black");
        car.setModel("bmw x5");
        car.setVolume("3.0L");
        car.setYear(2018);

        System.out.println(objectToMap(car));
    }

    /**
     * 将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();
        for (Field field : clazz.getDeclaredFields()) {
            field.setAccessible(true);
            String fieldName = field.getName();
            Object value = StringUtils.nvl(field.get(obj));
            map.put(fieldName, value);
        }
        return map;
    }
}

输出

{volume=3.0L, color=black, year=2018, model=bmw x5, id=00000}

 

posted @ 2019-01-03 22:48  京大雄  阅读(120757)  评论(2编辑  收藏  举报