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

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

对于实现,主要是使用 java 的反射机制。

首先需要构造一个实体类(TestModel.java):

package test;

public class TestModel {

private String prop1;    
private String prop2;
private String prop3;    


public String getProp1() {
return prop1;
}
public void setProp1(String prop1) {
this.prop1 = prop1;
}
public String getProp2() {
return prop2;
}
public void setProp2(String prop2) {
this.prop2 = prop2;
}
public String getProp3() {
return prop3;
}
public void setProp3(String prop3) {
this.prop3 = prop3;
}

//用于输出字符串
@Override
public String toString() {

return "prop1:"+prop1+"
prop2:"+prop2+"
prop3:"+prop3;
}
}

然后紧接着创建一个合并相同实体的功能类():

package test;
import java.lang.reflect.Field;

public class CombineBeans {
    
    
    /**
     * 该方法是用于相同对象不同属性值的合并,如果两个相同对象中同一属性都有值,那么sourceBean中的值会覆盖tagetBean重点的值
     * @param sourceBean    被提取的对象bean
     * @param targetBean    用于合并的对象bean
     * @return targetBean,合并后的对象
     */
    private TestModel 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<sourceFields.length; 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(); } } return targetBean; } //测试 combineBeans方法 public static void main(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 = new CombineBeans(); test.combineSydwCore(sourceModel, targetModel); System.out.println(targetModel.toString()); } }

输出的结果如下:

根据控制台中打印结果发现:

原来的targetModel属性值:

prop1:null
prop2:2
prop3:2

合并之后的targetModel属性值:

prop1:1
prop2:1
prop3:2

targetModel中的 prop1 属性被 sourceModel 中的 prop1 属性填充;prop2 属性被 prop1 覆盖。

到此,over !!! ^_^

 -----------------------------

 在后续使用中发现,应该排除 静态域,具体判断方法参考:https://blog.csdn.net/zhou8622/article/details/44038699

Read the fucking manual and source code
原文地址:https://www.cnblogs.com/qxynotebook/p/5680228.html