CombineBeansUtil.java
package com.network.utils;

import java.lang.reflect.Field;
import java.lang.reflect.Modifier;

/**
 * @Description: 对象合并的工具类
 * @author victor
 */
public class CombineBeansUtil {

    /**
     ** 该方法是用于相同对象不同属性值的合并<br>
     ** 如果两个相同对象中同一属性都有值,那么sourceBean中的值会覆盖tagetBean重点的值<br>
     ** 如果sourceBean有值,targetBean没有,则采用sourceBean的值<br>
     ** 如果sourceBean没有值,targetBean有,则保留targetBean的值
     * 
     * @param sourceBean    被提取的对象bean
     * @param targetBean    用于合并的对象bean
     * @return targetBean,合并后的对象
     */
    public static <T> T combineSydwCore(T sourceBean, T targetBean){
        Class<? extends Object> sourceBeanClass = sourceBean.getClass();
        Class<? extends Object> 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;
    }
}

测试

public static void main(String[] args) {
        User sourceS = new User(); // 第一个对象
        User targetS = new User(); // 第二个User对象
 
        sourceS.setSex("1");
        sourceS.setcName("张三");
 
        targetS.setSex("2");
        targetS.setcName("李四");
        targetS.setAge(24);
        targetS.setSalary("18888");
 
        System.out.pringln(CombineBeansUtil.combineSydwCore(sourceS, targetS));
}

 

追崇技术,乐在分享!