java中对象和Map互相转换的几种方式
在Java中,可以使用反射机制将对象转换为Map,同时也可以将Map转换为对象。以下是几种常见的方法:
- 使用Apache Commons BeanUtils库
import org.apache.commons.beanutils.BeanUtils;
// 将对象转换为Map
public Map<String, Object> objectToMap(Object obj) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException {
Map<String, Object> map = new HashMap<>();
BeanInfo beanInfo = Introspector.getBeanInfo(obj.getClass());
PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
for (PropertyDescriptor pd : propertyDescriptors) {
String propertyName = pd.getName();
if (!"class".equals(propertyName)) {
Method readMethod = pd.getReadMethod();
Object result = readMethod.invoke(obj);
map.put(propertyName, result);
}
}
return map;
}
// 将Map转换为对象
public Object mapToObject(Map<String, Object> map, Class<?> objClass) throws IllegalAccessException, InstantiationException, InvocationTargetException {
Object obj = objClass.newInstance();
BeanUtils.populate(obj, map);
return obj;
}
- 使用Java Reflection API
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
// 将对象转换为Map
public 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;
}
// 将Map转换为对象
public Object mapToObject(Map<String, Object> map, Class<?> objClass) throws IllegalAccessException, InstantiationException {
Object obj = objClass.newInstance();
for (Map.Entry<String, Object> entry : map.entrySet()) {
Field field = objClass.getDeclaredField(entry.getKey());
field.setAccessible(true);
field.set(obj, entry.getValue());
}
return obj;
}
- 使用Jackson库
import com.fasterxml.jackson.databind.ObjectMapper;
// 将对象转换为Map
public Map<String, Object> objectToMap(Object obj) throws IOException {
ObjectMapper objectMap
评论已关闭