javabean反射改字段内容_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 genValueByGenerics(Class> clazz,Class> seviceClz,E entity) {

Map resutlMap = new LinkedHashMap();

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 genSetMethodCode(Class> clz) {

List 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 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 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 map = new HashMap();

//获取指定方法运行结果

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 {

@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 getDao() {

return creditRatingFileApplyDao;

}

public List queryByParam(Map params){

return creditRatingFileApplyDao.queryByParam(params);

}

public String getHomeValue(Map params){

List list = creditRatingFileApplyDao.getHomeValue(params);

if (null != list&&list.size()>0) {

return list.get(0);

}

return "";

}

public String getCarName(Map params){

List list = creditRatingFileApplyDao.getCarName(params);

if (null != list&&list.size()>0) {

return list.get(0);

}

return "";

}

public String getCarNum(Map params){

List list = creditRatingFileApplyDao.getCarNum(params);

if (null != list&&list.size()>0) {

return list.get(0);

}

return "";

}

public String getCarValue(Map params){

List list = creditRatingFileApplyDao.getCarValue(params);

if (null != list&&list.size()>0) {

return list.get(0);

}

return "";

}

public String getAssetSum(Map params){

List list = creditRatingFileApplyDao.getAssetSum(params);

if (null != list&&list.size()>0) {

return list.get(0);

}

return "";

}

public String getBusinessAsset1(Map params){

List list = creditRatingFileApplyDao.getBusinessAsset1(params);

if (null != list&&list.size()>0) {

return list.get(0);

}

return "";

}

public String getYear1FamilyIncome(Map params){

List list = creditRatingFileApplyDao.getYear1FamilyIncome(params);

if (null != list&&list.size()>0) {

return list.get(0);

}

return "";

}

public String getYear1DebtSum(Map params){

List list = creditRatingFileApplyDao.getYear1DebtSum(params);

if (null != list&&list.size()>0) {

return list.get(0);

}

return "";

}

public String getYear2FamilyIncome(Map params){

List list = creditRatingFileApplyDao.getYear2FamilyIncome(params);

if (null != list&&list.size()>0) {

return list.get(0);

}

return "";

}

public String getYear2DebtSum(Map params){

List list = creditRatingFileApplyDao.getYear2DebtSum(params);

if (null != list&&list.size()>0) {

return list.get(0);

}

return "";

}

public String getYear3FamilyIncome(Map params){

List list = creditRatingFileApplyDao.getYear3FamilyIncome(params);

if (null != list&&list.size()>0) {

return list.get(0);

}

return "";

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值