JAVA两个对象属性合并

来源:互联网 发布:学云计算用了解嵌入式 编辑:程序博客网 时间:2024/05/16 13:47
import java.lang.reflect.Field;import com.alibaba.fastjson.JSON;import com.mmh.core.model.ProductOrder;public class CombineBeans {            /**     *      * @param sourceBean    被提取的对象bean     * @param targetBean    用于合并的对象bean     * @return targetBean,合并后的对象     */    /**      * @Title: combineSydwCore      * @Description: 该方法是用于相同对象不同属性值的合并,如果两个相同对象中同一属性都有值,那么sourceBean中的值会覆盖tagetBean重点的值     * @author: WangLongFei     * @date: 2017年12月26日 下午1:53:19      * @param sourceBean    被提取的对象bean     * @param targetBean    用于合并的对象bean     * @return targetBean 合并后的对象     * @return: Object     */    private Object combineSydwCore(Object sourceBean,Object targetBean){        Class sourceBeanClass = sourceBean.getClass();        Class targetBeanClass = targetBean.getClass();                Field[] sourceFields = sourceBeanClass.getDeclaredFields();        Field[] targetFields = sourceBeanClass.getDeclaredFields();        for(int i=0; i<sourceFields.length; i++){            Field sourceField = sourceFields[i];             Field targetField = targetFields[i];              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) {        ProductOrder sourceModel = new ProductOrder();    //    第一个对象        ProductOrder targetModel = new ProductOrder();    //    第二个model对象                sourceModel.setSex("1");        sourceModel.setcName("张三");                targetModel.setSex("1");        targetModel.setcName("张三");        targetModel.setCardName("身份证");        targetModel.setCardNumber("222222222222222222222");                CombineBeans test = new CombineBeans();        test.combineSydwCore(sourceModel, targetModel);                System.out.println(JSON.toJSONString(targetModel));    }}

阅读全文
'); })();
0 0
原创粉丝点击
热门IT博客
热门问题 老师的惩罚 人脸识别 我在镇武司摸鱼那些年 重生之率土为王 我在大康的咸鱼生活 盘龙之生命进化 天生仙种 凡人之先天五行 春回大明朝 姑娘不必设防,我是瞎子 侠岚第四季 侠岚第二季 侠岚第一季 侠岚第三季 龙魂侠影 萍踪侠影 侠影仙踪 萍踪侠影录 龙魂侠影txt 侠影记 新萍踪侠影 侠影之谜 侠影神剑 龙魂侠影txt全集下载 龙形侠影黄澄可 仙踪侠影叶辰 龙魂侠影番外篇1一17 霹雳侠影之轰定干戈 萍踪侠影录85版全集 龙魂侠影下载 萍踪侠影85版 龙魂侠影 admin 评书萍踪侠影 都市之天王太子爷 侠影之谜 少侠奇情 江湖侠情 侠情剑雨 金猫侠 金猫侠说段子大全 累趴侠下载 仙道侠缘浮云闲人 侠踪仙影 侠捕之诡影迷踪 侠影迷踪 侠隐 侠饭 侠饭第一季 我从漫威世界归来 饭桶侠 侠骨柔情 侠骨仁心 侠骨香