Original: http://www.open-open.com/code/view/1423280939826
/** * Use org.apache.commons.beanutils for conversion/class A {public static Object Maptoobject (map<string, O
bject> 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 Nu
ll
return new Org.apache.commons.beanutils.BeanMap (obj); }/** * Using Introspector for conversion/class B {public static Object Maptoobject (map<string, O
bject> map, class<?> beanclass) throws Exception {if (map = = NULL) return null;
Object obj = beanclass.newinstance ();
BeanInfo BeanInfo = Introspector.getbeaninfo (Obj.getclass ()); Propertydescriptor[] Propertydescriptors = Beaninfo.getpropertydescriptors ();
for (PropertyDescriptor property:propertydescriptors) {Method setter = Property.getwritemethod ();
if (setter!= null) {Setter.invoke (obj, Map.get (Property.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> ();
BeanInfo BeanInfo = Introspector.getbeaninfo (Obj.getclass ());
propertydescriptor[] PropertyDescriptors = Beaninfo.getpropertydescriptors ();
for (PropertyDescriptor property:propertydescriptors) {String key = Property.getname ();
if (Key.comparetoignorecase ("class") = = 0) {continue; } Method Getter = Property.getreadmethod (); Object value = getter!=null?
Getter.invoke (obj): null;
Map.put (key, value);
} return map; }/** * using reflect for conversion/class C {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; }
}