CombineBeansUtil:方法是用于相同对象不同属性值的合并

今天碰到了两个Bean合并的案例。这里保留一份找来的工具类,修改了下。
注意:方法是用于相同对象不同属性值的合并

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

/**
 * Description: 对象合并的工具类
 *
 * @author
 * @date 2018-09-11 上午11:27
 */
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 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;
    }

}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容