Java 反射機制的應用實例
2017.12.15 14:20
8009瀏覽
Java 反射機制的應用實例
前言:
反射是java中一種強大的工具,能夠使我們很方便的創建靈活的代碼,這些代碼可以再運行時裝配,無需在組件之間進行源代碼鏈接。主要是指程序可以訪問,檢測和修改它本身狀態或行為的一種能力,并能根據自身行為的狀態和結果,調整或修改應用所描述行為的狀態和相關的語義。
下面介紹倆個在實際運用中反射的應用:
場景一:DTO的數據封裝
在大多數軟件架構中有一層DTO層,用于提供于與前端的數據交互。示意如下圖:
數據傳輸對象(DTO)(Data Transfer Object),是一種設計模式之間傳輸數據的軟件應用系統。數據傳輸目標往往是數據訪問對象從數據庫中檢索數據。數據傳輸對象與數據交互對象或數據訪問對象之間的差異是一個以不具有任何行為除了存儲和檢索的數據(訪問和存取器)。
例如,我們要給APP端提供用戶信息,將要用到的數據封裝到UserModel,然后利用反射,提交給前端。
/**
* 獲取用戶資料
*
* @param userId
* @return
*/
@RequestMapping(value=Router.User.GET_USER_BASIC_INFORMATION,method=RequestMethod.POST)
@ResponseBody
public Response get_user_basic_information(@RequestParam("userId") int userId) {
log.info("infoMsg:--- 獲取用戶資料開始");
Response reponse = this.getReponse();
UserModel model = new UserModel();
try {
UserEntity user = appUserService.findById(userId);
if(user != null) {
mergeEneity(user, model);
}
log.info("infoMsg:--- 獲取用戶資料結束");
return reponse.success(model);
} catch (Exception e) {
log.error("errorMsg:{--- 獲取用戶資料失敗:" + e.getMessage() + "---}");
return reponse.failure(e.getMessage());
}
}
/**
* 合并倆個對象,并驗證get、set方法是否一致
* @param targetBean
* @param sourceBean
* @return
*/
public static Object mergeEneity(Object targetBean, Object sourceBean){
if(targetBean == null || sourceBean == null){
return targetBean;
}
Method[] sourceBeanMethods = sourceBean.getClass().getMethods();
Method[] targetBeanMethods = targetBean.getClass().getMethods();
for(Method m : sourceBeanMethods){
if(m.getName().indexOf("get") > -1){
String set = m.getName().replaceFirst("g", "s");
for(Method t : targetBeanMethods){
if(set.equals(t.getName())){
try {
Object res = m.invoke(sourceBean);
if(null != res){
t.invoke(targetBean, res);
}
break;
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
}
}
}
return targetBean;
}
場景二:因為業務原因在修改個人資料的時候,只修改資料中隨機一個字段的信息,所以為了簡化抽象,利用了反射。
/**
* 編輯用戶資料
*
* @param userId
* @param fieldName
* @param fieldValue
* @return
*/
@RequestMapping(value=Router.User.EDIT_USER_INFORMATION,method=RequestMethod.POST)
@ResponseBody
public Response edit_user_information(@RequestParam("userId") int userId,
@RequestParam("fieldName") String fieldName,@RequestParam("fieldValue") String fieldValue) {
log.info("infoMsg:--- 用戶修改資料開始");
Response reponse = this.getReponse();
try {
PageData pd = new PageData<>();
pd.put("userId", userId);
pd.put("fieldName", fieldName);
pd.put("fieldValue", fieldValue);
appUserService.edit_user_information(pd);
log.info("infoMsg:--- 用戶修改資料結束");
return reponse.failure();
} catch (Exception e) {
log.error("errorMsg:{---用戶修改資料失敗:" + e.getMessage() + "---}");
return reponse.failure(e.getMessage());
}
}
/**
* 編輯用戶資料
*
* @param pd
* @throws InvocationTargetException
* @throws IllegalArgumentException
* @throws IllegalAccessException
*/
public void edit_user_information(PageData pd) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException {
int userId = (int) pd.get("userId");
UserEntity user = appUserDao.findById(userId);
String fieldName = pd.getString("fieldName");
String fieldValue = pd.getString("fieldValue");
Method[] methods = user.getClass().getMethods();
Field[] fields = user.getClass().getFields();
for(Field fidle : fields) {
if(fieldName.equals(fidle.getName())) {
for(Method m : methods) {
if(m.getName().equalsIgnoreCase("set" + fieldName)) {
// m.invoke(fieldName, fieldValue);
m.invoke(fieldValue, user);
appUserDao.edit_user_information(pd);
}
}
}
}
}
點擊查看更多內容
本文原創發布于慕課網 ,轉載請注明出處,謝謝合作
9人點贊
評論
共同學習,寫下你的評論
評論加載中...
相關文章推薦
正在加載中
慕課專欄
更多