您的位置:首页 > 编程语言 > Java开发

合并两个java bean对象非空属性(泛型)

2016-06-07 07:36 567 查看
import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;

class Beanutils{
//merge two bean by discovering differences
public static <M> void merge(M target, M destination) throws Exception {
BeanInfo beanInfo = Introspector.getBeanInfo(target.getClass());

// Iterate over all the attributes
for (PropertyDescriptor descriptor : beanInfo.getPropertyDescriptors()) {

// Only copy writable attributes
if (descriptor.getWriteMethod() != null) {
Object originalValue = descriptor.getReadMethod()
.invoke(target);

// Only copy values values where the destination values is null
if (originalValue == null) {
Object defaultValue = descriptor.getReadMethod().invoke(
destination);
descriptor.getWriteMethod().invoke(target, defaultValue);
}

}
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: