原文地址:
3358 www.open-open.com/code/view/1423280939826
使用org.apache.commons.beanutils进行转换。 该方案还可以赋值从父类继承的属性字段,并且是可靠的。
公共静态对象映射(mapstring,objectmap,Class? beanclass(throwsexception(if ) map==null ) return null; objectobj=bean class.new instance (; org.Apache.com mons.beanutils.beanutils.populate (obj,map ); 返回对象; }公共静态图? objecttomap(objectobj ) if ) obj==null ) return null; return new org.Apache.com mons.beanutils.bean map (obj ) }2.使用Java的reflect进行转换,并将转换后的对象正确地分配给父类字段
公共静态对象映射(mapstring,objectmap,Class? beanclass(throwsexception(if ) map==null ) return null; objectobj=bean class.new instance (; Field[] fields=obj.getClass ().getDeclaredFields; 字段字段:字段(intmod=field.get modifiers ); modifier.is静态(mod ) ) { continue; }field.setaccessible(true; field.set(obj,map.get ) field.getname ) ); } return obj; }公共静态映射,objectobjecttomap(objectobj ) throwsexception(if ) obj==null ) { return null; } MapString,Object map=new HashMapString,Object (; field [ ] declared fields=obj.getclass ().getDeclaredFields; 场域:取消场域(for ) field.setaccessible(true ); map.put(field.getname )、field.get (obj ); }返回地图; 63 .结束