//pojo转map
public static Map<String, Object> pojo2Map(Object obj) throws Exception{
Map<String, Object> map = new HashMap<String, Object>();Class<?> clazz = obj.getClass();
Field[] fields = clazz.getDeclaredFields();
for (Field field : fields) {
PropertyDescriptor pd = new PropertyDescriptor(field.getName(), clazz);
Method getMethod = pd.getReadMethod();
Object o = getMethod.invoke(obj);
map.put(field.getName(), o);
}
return map;
}
//Map 转 pojo对象
public static Object map2Object(Map<String, Object> map, Class<?> beanClass) throws Exception {
if (map == null)
return null;
Object obj = beanClass.newInstance();
org.apache.commons.beanutils.BeanUtils.populate(obj, map);
return obj;
}
本文提供了一种将POJO对象转换为Map以及从Map创建POJO对象的方法。使用反射和BeanUtils工具类实现了这两个功能。

2226

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



