如何用BeanUtils把一个对象中的属性值复制到另一个对象中和BeanUtils中的方法

场景:当其他系统调用我们的一个接口进行一些业务数据的修改,通过接口传过来一个user对象,但不含有user的uuid,这样就不能直接保存达到修改的目的,一般情况下我们先通过tradeCode交易编号找到之前的user,然后通过set方法把新user中的值放入之前的user中然后保存达到修改目的,或者把之前的user删除再保存新的user达到修改的目的。感觉都不是很好,在BeanUtils中提供了copyProperties的多种重载方法可以很方便的达到此目的。
实例代码:

AgentInfoEntity oldAgentInfo = agentInfoDao.FindAgentInfoByTradeCode(businessInfoEntity.getTradeCode());
AgentInfoEntity agentInfo = tradeEvidenceModel.getTradeInfo().getAgentInfo();
BeanUtils.copyProperties(agentInfo, oldAgentInfo,"uuid","businessCode","tradeCode","caseCategoryCode");
agentInfoDao.saveOrUpdate(oldAgentInfo);

说明:oldAgentInfo 老的对象,agentInfo 新的对象,把agentInfo中的值放入oldAgentInfo中,并忽略"uuid",“businessCode”,“tradeCode”,“caseCategoryCode”,不然如果agentInfo这些值没有,oldAgentInfo中会被致成null。

在这里插入图片描述
BeanUtils中有各种利用反射获得一个类中属性,方法的方法

猜你喜欢

转载自blog.csdn.net/shidebin/article/details/84066986