java类的合并_对于两个实体类属性值的合并,java实现

packagetest;importjava.lang.reflect.Field;public classCombineBeans {/*** 该方法是用于相同对象不同属性值的合并,如果两个相同对象中同一属性都有值,那么sourceBean中的值会覆盖tagetBean重点的值

*@paramsourceBean 被提取的对象bean

*@paramtargetBean 用于合并的对象bean

*@returntargetBean,合并后的对象*/

privateTestModel combineSydwCore(TestModel sourceBean,TestModel targetBean){

Class sourceBeanClass=sourceBean.getClass();

Class targetBeanClass=targetBean.getClass();

Field[] sourceFields=sourceBeanClass.getDeclaredFields();

Field[] targetFields=targetBeanClass.getDeclaredFields();for(int i=0; i

Field sourceField=sourceFields[i];

if(Modifier.isStatic(sourceField.getModifiers())){

continue;

}

Field targetField=targetFields[i];

if(Modifier.isStatic(targetField.getModifiers())){

continue;

}

sourceField.setAccessible(true);

targetField.setAccessible(true);try{if( !(sourceField.get(sourceBean) == null) && !"serialVersionUID".equals(sourceField.getName().toString())){

targetField.set(targetBean,sourceField.get(sourceBean));

}

}catch (IllegalArgumentException |IllegalAccessException e) {

e.printStackTrace();

}

}returntargetBean;

}//测试 combineBeans方法

public static voidmain(String[] args) {

TestModel sourceModel= new TestModel(); //第一个对象

TestModel targetModel = new TestModel(); //第二个model对象

sourceModel.setProp1("1");

sourceModel.setProp2("1");

targetModel.setProp2("2");

targetModel.setProp3("2");

CombineBeans test= newCombineBeans();

test.combineSydwCore(sourceModel, targetModel);

System.out.println(targetModel.toString());

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值