public static Map<String, Object> beanToMap(Object requestBody, String[] excludeField) {
if (requestBody == null) {
return null;
}
List<Field> fields = new ArrayList<>();
// 当父类为null的时候说明到达了最上层的父类(Object类)
Class tempClass = requestBody.getClass();
while (tempClass != null) {
fields.addAll(Arrays.asList(tempClass.getDeclaredFields()));
// 得到父类,然后赋给自己
tempClass = tempClass.getSuperclass();
}
/*=====迭代属性排序=====*/
Map<String, Object> fieldMap = new TreeMap<>();
for (Field field : fields) {
String name = field.getName();
if (excludeField != null && Arrays.asList(excludeField).contains(name)) {
System.out.println("剔除属性:"+name);
continue;
}
field.setAccessible(true);
Object value = null;
try {
value = field.get(requestBody);
} catch (IllegalAccessException e) {
System.out.println("反射获取对象属性值异常:"+e);
}
if (StringUtils.isNotBlank((String) value)) {
fieldMap.put(name, value.toString());
}
}
return fieldMap;
}