方式一通过反射的方法,通过属性字段操作
public static Map<String, Object> bean2Map1(Object obj) throws IllegalAccessException {
if (obj == null)
return Collections.EMPTY_MAP;
Map<String,Object> map = new HashMap<>();
//获取所有的属性
Field[] fields = obj.getClass().getDeclaredFields();
for (Field field : fields){
//设置属性是可以进入的,私有属性也可以进入
field.setAccessible(true);
map.put(field.getName(),field.get(obj));
}
return map;
}
public static <T> T map2Bean1(Map<String,Object> map, Class<T> clazz) throws IllegalAccessException, InstantiationException, NoSuchFieldException {
if (map == null)
return null;
T obj = clazz.newInstance();
Set<String> keys = map.keySet();
for (String key : keys){
Field field = clazz.getDeclaredField(key);
field.setAccessible(true);
field.set(obj,map.get(key));
}
return obj;
}
方式2,通过内省,通过属性的读写方法进行设置
public static Map<String,Object> bean2Map2(Object obj) throws IntrospectionException, InvocationTargetException, IllegalAccessException {
if (obj == null)
return Collections.EMPTY_MAP;
Map<String,Object> map = new HashMap<>();
BeanInfo beanInfo = Introspector.getBeanInfo(obj.getClass());
//通过beanInfo获取属性描述
PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
for (PropertyDescriptor propertyDescriptor : propertyDescriptors){
String key = propertyDescriptor.getName();
if (!"class".equals(key)) {
Method getter = propertyDescriptor.getReadMethod();
Object value = getter.invoke(obj);
map.put(key, value);
}
}
return map;
}
public static <T> T map2Bean2(Map<String, Object> map, Class<T> clazz) throws IllegalAccessException, InstantiationException, IntrospectionException, InvocationTargetException {
if (map == null)
return null;
T obj = clazz.newInstance();
Set<String> set = map.keySet();
BeanInfo beanInfo = Introspector.getBeanInfo(clazz);
PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
for (PropertyDescriptor propertyDescriptor : propertyDescriptors){
String key = propertyDescriptor.getName();
if (!"class".equals(key)) {
Method writer = propertyDescriptor.getWriteMethod();
writer.invoke(obj, map.get(key));
}
}
return obj;
}
//方式3,使用BeanUtils工具类
public static Map<String,Object> bean2Map3(Object obj) throws Exception {
if (obj == null)
return Collections.EMPTY_MAP;
return BeanUtils.describe(obj);
}
public static <T> T map2Bean3(Map<String, Object> map, Class<T> beanClass) throws Exception {
if (map == null)
return null;
T obj = beanClass.newInstance();
BeanUtils.populate(obj, map);
return obj;
}

本文详细介绍三种将Java对象转换为Map及从Map转换回Java对象的方法:通过反射操作属性字段,利用内省通过属性的读写方法进行设置,以及使用BeanUtils工具类简化操作。适用于Java开发者理解和掌握对象与Map之间的转换技巧。
4437

被折叠的 条评论
为什么被折叠?



