java利用反射机制完成JavaBean的属性赋值
今天碰到一个场景,就是一个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 "";
}
}
上一篇: 诙谐一句话短笑话
下一篇: 男女相亲闹的爆笑交流