Apache的BeanUtils Bean工具類很強大,基本涵蓋了Bean操做的全部方法。這裏的話咱們就講講兩個方面,一是Bean covert to Map,二是Map covert to Bean;Bean轉Map其實利用的是Java的動態性-Reflection技術,無論是什麼Bean經過動態解析都是能夠轉成Map對象的,但前提條件是field須要符合駝峯命名不過這也是寫碼規範,另外一個條件就是每一個field須要getter、setter方法。而Map轉Bean同樣也是經過Reflection動態解析成Bean。Java的Reflection實際上是挺重要的,咱們用的不少工具類都有它的存在,咱們不止要會用並且更重要的是可以理解是爲何,最好是本身去手寫實現這樣的話更能加深理解。算法
1 /** 2 * 用apache的BeanUtils實現Bean covert to Map 3 * @throws Exception 4 */ 5 public static void beanToMap() throws Exception { 6 User user=new User(); 7 Map<String,String> keyValues=null; 8 9 user.setPassWord("password"); 10 user.setComments("test method!"); 11 user.setUserName("wang shisheng"); 12 user.setCreateTime(new Date()); 13 14 keyValues=BeanUtils.describe(user); 15 16 LOGGER.info("bean covert to map:{}", JSONObject.toJSON(keyValues).toString()); 17 }
1 /** 2 * 用apache的BeanUtils實現Map covert to Bean 3 * @throws Exception 4 */ 5 public static void mapToBean() throws Exception { 6 Map<String,String> keyValues=new HashMap<>(); 7 User user=new User(); 8 9 keyValues.put("sessionId","ED442323232ff3"); 10 keyValues.put("userName","wang shisheng"); 11 keyValues.put("passWord","xxxxx44333"); 12 keyValues.put("requestNums","34"); 13 14 BeanUtils.populate(user,keyValues); 15 16 LOGGER.info("map covert to bean:{}", user.toString()); 17 }
/** * 應用反射(其實工具類底層同樣用的反射技術) * 手動寫一個 Bean covert to Map */ public static void autoBeanToMap(){ User user=new User(); Map<String,Object> keyValues=new HashMap<>(); user.setPassWord("password"); user.setComments("test method!"); user.setUserName("wang shisheng"); user.setUserCode("2018998770"); user.setCreateTime(new Date()); Method[] methods=user.getClass().getMethods(); try { for(Method method: methods){ String methodName=method.getName(); //反射獲取屬性與屬性值的方法不少,如下是其一;也能夠直接得到屬性,不過獲取的時候須要用過設置屬性私有可見 if (methodName.contains("get")){ //invoke 執行get方法獲取屬性值 Object value=method.invoke(user); //根據setXXXX 經過如下算法取得屬性名稱 String key=methodName.substring(methodName.indexOf("get")+3); Object temp=key.substring(0,1).toString().toLowerCase(); key=key.substring(1); //最終獲得屬性名稱 key=temp+key; keyValues.put(key,value); } } }catch (Exception e){ LOGGER.error("錯誤信息:",e); } LOGGER.info("auto bean covert to map:{}", JSONObject.toJSON(keyValues).toString()); }