java合並相同對象不同屬性Bean


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));
}

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM