今天碰到一個場景,就是一個JavaBean,有些屬性的值需要去資料庫其他表中獲取,這樣就需要調用其他dao方法得到這個值,然後再set進去。 可是問題來了,如果需要用這種方式賦值的屬性特別多的話,一個一個set進去就需要寫很多set方法,代碼不僅冗餘,而且很麻煩。 於是就想通過反射機制去自動set值 ...
今天碰到一個場景,就是一個JavaBean,有些屬性的值需要去資料庫其他表中獲取,這樣就需要調用其他dao方法得到這個值,然後再set進去。
可是問題來了,如果需要用這種方式賦值的屬性特別多的話,一個一個set進去就需要寫很多set方法,代碼不僅冗餘,而且很麻煩。
於是就想通過反射機制去自動set值。
假設有JavaBean為CreditRatingFile.java類,某些屬性值需要調用CreditRatingFileApplyService類中的方法獲得,並拿到返回值再set出這些屬性。
一、拿到所有JavaBean為CreditRatingFile.java類的屬性
二、拿到多有CreditRatingFileApplyService類的方法
三、匹配之後再根據CreditRatingFile.java的setter方法set對應CreditRatingFileApplyService類方法的返回值
貼出代碼:
反射工具類:
package com.krm.modules.creditFileApplay.util;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import com.krm.modules.creditFileApplay.model.CreditRatingFile;
import com.krm.modules.creditFileApplay.service.CreditRatingFileApplyService;
import com.thinkgem.jeesite.common.utils.Reflections;
public class ReflectUtil {
@SuppressWarnings("unused")
public static <E> E genValueByGenerics(Class<?> clazz,Class<?> seviceClz,E entity) {
Map<String, Field> resutlMap = new LinkedHashMap<String, Field>();
for (; clazz != Object.class; clazz = clazz.getSuperclass()) {
Field[] fields = clazz.getDeclaredFields();
for (Field field : fields) {
resutlMap.put(field.getName(), field);
// System.out.println(field.getName());
//獲取到javaBean中所有屬性後,通過反射機制與service所有方法匹配
String toServiceMethodName = "get"+field.getName().substring(0, 1).toUpperCase()+field.getName().substring(1, field.getName().length());
if ("getCreditLimit2".equals(toServiceMethodName) || "getCreditRatingLevel3".equals(toServiceMethodName)) {
doServiceMethod(seviceClz,toServiceMethodName,entity,field.getName());
}
}
}
return entity;
}
public static void bianLi(Object obj){
Field[] fields = obj.getClass().getDeclaredFields();
for(int i = 0 , len = fields.length; i < len; i++) {
// 對於每個屬性,獲取屬性名
String varName = fields[i].getName();
try {
// 獲取原來的訪問控制許可權
boolean accessFlag = fields[i].isAccessible();
// 修改訪問控制許可權
fields[i].setAccessible(true);
// 獲取在對象f中屬性fields[i]對應的對象中的變數
Object o;
try {
o = fields[i].get(obj);
System.err.println("傳入的對象中包含一個如下的變數:" + varName + " = " + o);
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// 恢復訪問控制許可權
fields[i].setAccessible(accessFlag);
} catch (IllegalArgumentException ex) {
ex.printStackTrace();
}
}
}
/**
* 獲得所有方法
* @param clz
* @return
*/
public static List<String> genSetMethodCode(Class<?> clz) {
List<String> setMethods = new ArrayList<>();
Method[] declaredMethods = clz.getDeclaredMethods();
String name = clz.getName();
int dot = name.lastIndexOf(".");
String objName = name.substring(dot+1, dot+2).toLowerCase() + name.substring(dot+2);
for (Method declaredMethod : declaredMethods) {
String methodName = declaredMethod.getName();
setMethods.add(objName + "." + methodName + "();");
}
for (String string : setMethods) {
System.out.println(string);
}
return setMethods;
}
/**
* 獲取指定service類的所有方法,並調用
* @param clz
*/
public static <E> void doServiceMethod(Class<?> clz,String beanAttribute,E entity,String propertyName){
Method[] declaredMethods = clz.getDeclaredMethods();
for (Method declaredMethod : declaredMethods) {
String methodName = declaredMethod.getName();
if (beanAttribute.equals(methodName)) {
reflectMethod(methodName,clz,entity,propertyName);
}
}
}
public static <E> void reflectMethod(String methodName,Class<?> clz,E entity,String propertyName){
try {
//可以傳固定的某個類的具體路徑,也可以傳class的getName()參數。
// Class<?> cls = Class.forName("com.krm.modules.creditFileApplay.service.CreditRatingFileApplyService");/
Class<?> cls = Class.forName(clz.getName());
Object obj = cls.newInstance();
//第一個參數是被調用方法的名稱,後面接著這個方法的形參類型
Class[] argTypes=new Class[1];
argTypes[0]=Map.class;
Method setFunc = cls.getMethod(methodName,argTypes);
//取得方法後即可通過invoke方法調用,傳入被調用方法所在類的對象和實參,對象可以通過cls.newInstance取得
Map<String,Object> map = new HashMap<String,Object>();
//獲取指定方法運行結果
Object result = setFunc.invoke(obj,map);
//調用setter方法
Reflections.invokeSetter(entity, propertyName, result);
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
CreditRatingFile entity = new CreditRatingFile();
entity.setCreditLimit3("444");
genValueByGenerics(CreditRatingFile.class, CreditRatingFileApplyService.class,entity);
System.out.println("實體類通過反射機制獲取到的屬性值為:"+entity.getCreditLimit2());
System.out.println("實體類通過反射機制獲取到的屬性值為:"+entity.getCreditRatingLevel3());
System.out.println("實體類通過反射機制獲取到的屬性值為:"+entity.getCreditLimit3());
}
}
service類中的方法
public class CreditRatingFileApplyService extends MybatisBaseService<CreditRatingFileApply> {
@Resource
private CreditRatingFileApplyDao creditRatingFileApplyDao;
@Override
public String getTableName() {
return ConfigUtils.getValue("schema.configPlat") + ".CREDIT_RATING_FILE_APPLY";
}
@Override
public String getIdKey() {
return "id";
}
@Override
public MybatisBaseDao<CreditRatingFileApply> getDao() {
return creditRatingFileApplyDao;
}
public List<CreditRatingFileApply> queryByParam(Map<String, Object> params){
return creditRatingFileApplyDao.queryByParam(params);
}
public String getHomeValue(Map<String,Object> params){
List<String> list = creditRatingFileApplyDao.getHomeValue(params);
if (null != list&&list.size()>0) {
return list.get(0);
}
return "";
}
public String getCarName(Map<String,Object> params){
List<String> list = creditRatingFileApplyDao.getCarName(params);
if (null != list&&list.size()>0) {
return list.get(0);
}
return "";
}
public String getCarNum(Map<String,Object> params){
List<String> list = creditRatingFileApplyDao.getCarNum(params);
if (null != list&&list.size()>0) {
return list.get(0);
}
return "";
}
public String getCarValue(Map<String,Object> params){
List<String> list = creditRatingFileApplyDao.getCarValue(params);
if (null != list&&list.size()>0) {
return list.get(0);
}
return "";
}
public String getAssetSum(Map<String,Object> params){
List<String> list = creditRatingFileApplyDao.getAssetSum(params);
if (null != list&&list.size()>0) {
return list.get(0);
}
return "";
}
public String getBusinessAsset1(Map<String,Object> params){
List<String> list = creditRatingFileApplyDao.getBusinessAsset1(params);
if (null != list&&list.size()>0) {
return list.get(0);
}
return "";
}
public String getYear1FamilyIncome(Map<String,Object> params){
List<String> list = creditRatingFileApplyDao.getYear1FamilyIncome(params);
if (null != list&&list.size()>0) {
return list.get(0);
}
return "";
}
public String getYear1DebtSum(Map<String,Object> params){
List<String> list = creditRatingFileApplyDao.getYear1DebtSum(params);
if (null != list&&list.size()>0) {
return list.get(0);
}
return "";
}
public String getYear2FamilyIncome(Map<String,Object> params){
List<String> list = creditRatingFileApplyDao.getYear2FamilyIncome(params);
if (null != list&&list.size()>0) {
return list.get(0);
}
return "";
}
public String getYear2DebtSum(Map<String,Object> params){
List<String> list = creditRatingFileApplyDao.getYear2DebtSum(params);
if (null != list&&list.size()>0) {
return list.get(0);
}
return "";
}
public String getYear3FamilyIncome(Map<String,Object> params){
List<String> list = creditRatingFileApplyDao.getYear3FamilyIncome(params);
if (null != list&&list.size()>0) {
return list.get(0);
}
return "";
}
}