Words don't say much, the code is as follows
Package Com.study;import java.lang.reflect.field;import Java.util.hashmap;import java.util.map;/** * PackageName Com.study * Description please write Description. * USER:YH * time:2016/11/29 16:57 */public class maputil{/** * JavaBean Turn Map * @param object JavaBean * @return Conversion result MAP * @throws Exception */public static map<string, object> Beantomap (O Bject object) throws Exception {map<string, object> Map = new hashmap<string, object> (); Class cls = Object.getclass (); field[] fields = Cls.getdeclaredfields (); for (Field field:fields) {field.setaccessible (true); Map.put (Field.getname (), Field.get (object)); } return map; }/** * * @param map required to convert map * @param CLS Target JavaBean class object * @return Target class ' object ' @throws Except Ion */public static Object Maptobean (map<string, object> Map, Class cls) throws Exception { Object object = Cls.newinstance (); For (String Key:map.keySet ()) {Field temfiels = Cls.getdeclaredfield (key); Temfiels.setaccessible (TRUE); Temfiels.set (object, Map.get (key)); } return object; }}
A tool class for JavaBean and map conversions based on Java reflection