Java中将Object转换为Map的方法有以下几种:
public static Map<String, Object> objectToMap(Object obj) throws IllegalAccessException {
Map<String, Object> map = new HashMap<>();
Class<?> clazz = obj.getClass();
for (Field field : clazz.getDeclaredFields()) {
field.setAccessible(true);
map.put(field.getName(), field.get(obj));
}
return map;
}
public static Map<String, Object> objectToMap(Object obj) throws IntrospectionException, IllegalAccessException, InvocationTargetException {
Map<String, Object> map = new HashMap<>();
BeanInfo beanInfo = Introspector.getBeanInfo(obj.getClass());
PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
for (PropertyDescriptor propertyDescriptor : propertyDescriptors) {
String key = propertyDescriptor.getName();
if (!key.equals("class")) {
Method getter = propertyDescriptor.getReadMethod();
Object value = getter.invoke(obj);
map.put(key, value);
}
}
return map;
}
使用Apache Commons BeanUtils:
import org.apache.commons.beanutils.BeanUtils;
public static Map<String, Object> objectToMap(Object obj) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException {
Map<String, Object> map = new HashMap<>();
map = BeanUtils.describe(obj);
map.remove("class");
return map;
}
使用Spring的BeanUtils:
import org.springframework.beans.BeanUtils;
public static Map<String, Object> objectToMap(Object obj) {
Map<String, Object> map = new HashMap<>();
BeanUtils.copyProperties(obj, map);
return map;
}