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;
}
}
合并两个javabean
最新推荐文章于 2023-10-16 22:05:19 发布