常规方式
无法保持bean的顺序
public static<T> Map beanToMap(T bean){
Map map = new HashMap();
if (!ObjectUtils.isEmpty(bean)) {
BeanMap beanMap = BeanMap.create(bean);
for (Object key : beanMap.keySet()) {
map.put(key,beanMap.get(key));
}
}
return map;
}
按序输出
public static <T> Map<String, Object> bean2Map(T source) throws Exception {
Map result = new LinkedHashMap();
Class<?> aClass = source.getClass();
Field[] declaredFields = aClass.getDeclaredFields();
for (Field declaredField : declaredFields) {
declaredField.setAccessible(true);
result.put(declaredField.getName(), declaredField.get(source));
}
return result;
}
|