当我们需要写一个对象的修改是,由于数据库中的某些字段的非空限制,所以每次需要将非空的字段和需要修改的字段传递过来,或者还需要先调用数据库,再将其需要修改的字段重新一个一个set设置。这样不是很方便,所以我们可以将传递过来的数据直接覆盖,这样不管前段传递几个字段都方便,只需要将要修改的字段和可以表明该条数据的唯一标识传递过来即可。具体公共方法如下:
/**
* 功能 : 只复制source对象的非空属性到target对象上
*/
public static void copyNoNullProperties(Object source, Object target) throws BeansException {
Assert.notNull(source, "Source must not be null");
Assert.notNull(target, "Target must not be null");
Class<?> actualEditable = target.getClass();
PropertyDescriptor[] targetPds = BeanUtils.getPropertyDescriptors(actualEditable);
for (PropertyDescriptor targetPd : targetPds) {
if (targetPd.getWriteMethod() != null) {
PropertyDescriptor sourcePd = BeanUtils.getPropertyDescriptor(source.getClass(), targetPd.getName());
if (sourcePd != null && sourcePd.getReadMethod() != null) {
try {
Method readMethod = sourcePd.getReadMethod();
if (!Modifier.isPublic(readMethod.getDeclaringClass().getModifiers())) {
readMethod.setAccessible(true);
}
Object value = readMethod.invoke(source);
// 这里判断以下value是否为空 当然这里也能进行一些特殊要求的处理 例如绑定时格式转换等等
if (value != null) {
Method writeMethod = targetPd.getWriteMethod();
if (!Modifier.isPublic(writeMethod.getDeclaringClass().getModifiers())) {
writeMethod.setAccessible(true);
}
writeMethod.invoke(target, value);
}
} catch (Throwable ex) {
throw new FatalBeanException("Could not copy properties from source to target", ex);
}
}
}
}
}
有人说BeanUtils.copyProperties()和PropertyUtils.copyProperties()方法也可以,但是这个是将整个对象完全复制到另外一个对象里面。很明显与我们的预期不一样。所以具体还是参考如上代码块即可