合并两个javabean

2019/7/23 9:23:51 人评论 次浏览 分类:学习教程

package com.war4.util;

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

/**
 * @Author:
 * @Date: 2019/7/13 08:34
 * 合并两个javabean的属性值
 */
public class CombineBeans {
 
    public static   <T> T combineBeans(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( (targetField.get(targetBean) != null)){
                    sourceField.set(sourceBean,targetField.get(targetBean));
                }
            } catch (IllegalArgumentException | IllegalAccessException e) {
                e.printStackTrace();
            }
        }
        return sourceBean;
    }
}

相关资讯

    暂无相关的资讯...

共有访客发表了评论 网友评论

验证码: 看不清楚?
    -->