Java Bean與Map之間相互轉化的實現方法
概述
Apache的BeanUtils Bean工具類很強大,基本涵蓋了Bean操作的所有方法。這里的話我們就講講兩個方面,一是Bean covert to Map,二是Map covert to Bean;Bean轉Map其實利用的是Java的動態(tài)性-Reflection技術,不管是什么Bean通過動態(tài)解析都是可以轉成Map對象的,但前提條件是field需要符合駝峰命名不過這也是寫碼規(guī)范,另一個條件就是每個field需要getter、setter方法。而Map轉Bean一樣也是通過Reflection動態(tài)解析成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轉Bean
代碼實現
/**
* 用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());
}
測試結果

理解BeanUtils將Bean轉Map的實現之手寫B(tài)ean轉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 執(zhí)行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相互轉化內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
SpringBoot實現設置動態(tài)定時任務的方法詳解
這篇文章主要介紹了SpringBoot實現設置動態(tài)定時任務的方法詳解,SpringBoot是一個快速開發(fā)的Java框架,而動態(tài)定時任務是指可以在運行時動態(tài)添加、修改和刪除定時任務的功能,需要的朋友可以參考下2023-10-10

