需求總是千奇百怪,物件轉成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}