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;
}