Java Bean與Map之間相互轉化的實現
目錄樹
概述
Apache BeanUtils將Bean轉Map
Apache BeanUtils將Map轉Bean
理解BeanUtils將Bean轉Map的實現之手寫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
程式碼實現
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 }
測試結果
用Apache BeanUtils將Map轉Bean
程式碼實現
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 }
測試結果
理解BeanUtils將Bean轉Map的實現之手寫Bean轉Map
程式碼實現
/**
•應用反射(其實工具類底層一樣用的反射技術)
•手動寫一個 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());
}
測試結果
Linux公社的RSS地址 : ofollow,noindex" target="_blank">https://www.linuxidc.com/rssFeed.aspx
本文永久更新連結地址: https://www.linuxidc.com/Linux/2018-10/154637.htm