BeanUtils.copyProperties排除null属性的copy
import com.hourumiyue.system.SpringUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeanWrapper;
import org.springframework.beans.BeanWrapperImpl;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import java.util.HashSet;
import java.util.Set;
public class TestBeanUtiles {
public static String[] getNullPropertyNames (Object source) {
final BeanWrapper src = new BeanWrapperImpl(source);
java.beans.PropertyDescriptor[] pds = src.getPropertyDescriptors();
Set<String> emptyNames = new HashSet<String>();
for(java.beans.PropertyDescriptor pd : pds) {
Object srcValue = src.getPropertyValue(pd.getName());
if (srcValue == null) emptyNames.add(pd.getName());
}
String[] result = new String[emptyNames.size()];
return emptyNames.toArray(result);
}
//封装同名称属性复制,但是空属性不复制过去
public static void copyPropertiesIgnoreNull(Object src, Object target){
BeanUtils.copyProperties(src, target, getNullPropertyNames(src));
}
public static void main(String[] args) {
NewPerson newPerson = new NewPerson();
newPerson.setName("miyue");//前台用户更新过的数据,例如前台只修改了用户名
//下面我们假设是从数据库加载出来的老数据
OldPerson oldPerson = new OldPerson();
oldPerson.setSex("nv");
oldPerson.setAge(5);
//如果我们想把新数据更新到老数据这个对象里面,我们就可以借助BeanUtils.copyProperties()的方法如下:
//BeanUtils.copyProperties(newPerson, oldPerson);
copyPropertiesIgnoreNull(newPerson, oldPerson);
System.out.println(newPerson.toString());
System.out.println(oldPerson.toString());
}
}