Java Bean與Map之間相互轉化的實現方法
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其實是挺重要的,我們用的很多工具類都有它的存在,我們不止要會用而且更重要的是能夠理解是為什么,最好是自己去手寫實現這樣的話更能加深理解。
用Apache BeanUtils將Bean轉Map代碼實現
/** * 用apache的BeanUtils實現Bean covert to Map * @throws Exception */ public static void beanToMap() throws Exception { User user=new User(); Map<String,String> keyValues=null; user.setPassWord('password'); user.setComments('test method!'); user.setUserName('wang shisheng'); user.setCreateTime(new Date()); keyValues=BeanUtils.describe(user); LOGGER.info('bean covert to map:{}', JSONObject.toJSON(keyValues).toString()); }
測試結果
代碼實現
/** * 用apache的BeanUtils實現Map covert to Bean * @throws Exception */ public static void mapToBean() throws Exception { Map<String,String> keyValues=new HashMap<>(); User user=new User(); keyValues.put('sessionId','ED442323232ff3'); keyValues.put('userName','wang shisheng'); keyValues.put('passWord','xxxxx44333'); keyValues.put('requestNums','34'); BeanUtils.populate(user,keyValues); LOGGER.info('map covert to bean:{}', user.toString()); }
測試結果
代碼實現
/** * 應用反射(其實工具類底層一樣用的反射技術) * 手動寫一個 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()); }
測試結果
到此這篇關于Java Bean與Map之間相互轉化的實現方法的文章就介紹到這了,更多相關Java Bean與Map相互轉化內容請搜索好吧啦網以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持好吧啦網!
相關文章: