将实体类转化为有序的Map。
使用LinkedHashMap可以将Map变成有序的key-value类型。
实体类:
1 2 3 4
| Apple apple = new Apple(); apple.setName("红富士"); apple.setColor("红色"); apple.setCount(5);
|
转化:
1 2 3 4 5 6 7
| Map<String, Object> map = new LinkedHashMap<>(); Field[] fields = apple.getClass().getDeclaredFields(); for (Field field : fields) { field.setAccessible(true); String name = field.getName(); map.put(name, field.get(apple)); }
|
结果:
1
| 实体类转Map:{name=红富士, color=红色, count=5}
|