原文地址:
http://www.open-open.com/code/view/1423280939826
1.使用使用org.apache.commons.beanutils进行转换,该方式可以把继承自父类的属性字段也进行赋值,靠谱.
public static Object mapToObject(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;
}
public static Map<?, ?> objectToMap(Object obj) {
if(obj == null)
return null;
return new org.apache.commons.beanutils.BeanMap(obj);
}
2.使用java的reflect进行转换,转换后的对象继承父类的字段没有正确赋值
public static Object mapToObject(Map<String, Object> map, Class<?> beanClass) throws Exception {
if (map == null)
return null;
Object obj = beanClass.newInstance();
Field[] fields = obj.getClass().getDeclaredFields();
for (Field field : fields) {
int mod = field.getModifiers();
if(Modifier.isStatic(mod) || Modifier.isFinal(mod)){
continue;
}
field.setAccessible(true);
field.set(obj, map.get(field.getName()));
}
return obj;
}
public static Map<String, Object> objectToMap(Object obj) throws Exception {
if(obj == null){
return null;
}
Map<String, Object> map = new HashMap<String, Object>();
Field[] declaredFields = obj.getClass().getDeclaredFields();
for (Field field : declaredFields) {
field.setAccessible(true);
map.put(field.getName(), field.get(obj));
}
return map;
}
3.结束