在工作过程中,我们可能会遇到这么一个需求,就是对于同一个类的两个不同对象(就是不为空的属性各不同)怎么合并他们成一个对象,并且包含他们两个的所有属性。

因为要获取一个对象的所有属性,我们自然想到要用反射,于是就有了下面的代码:

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())){
                targetField.set(targetBean, sourceField.get(sourceBean));
            }
        } catch (IllegalArgumentException | IllegalAccessException e) {
            e.printStackTrace();
        }
    }
    return targetBean;
}


技术分享     

本博客所有文章除特别声明外,均采用 CC BY-SA 3.0协议 。转载请注明出处!