解决在使用spring的BeanUtils.copyProperties时,值为null的属性也复制的问题
把源对象中的属性值为null的属性名取出,复制时过滤
import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeanWrapper;
import org.springframework.beans.BeanWrapperImpl;
import java.util.HashSet;
import java.util.Set;
public class Test {
public static void main(String[] args) {
User user = new User();
user.setName("张三");
user.setAge(10);
System.out.println(user);
System.out.println("复制属性并且复制null============================");
User copyUser = new User();
copyUser.setName("李四");
copyUser.setAge(20);
copyUser.setSex("男");
System.out.println(copyUser);
BeanUtils.copyProperties(user, copyUser);
System.out.println(copyUser);
System.out.println("复制属性不复制null============================");
User copyUser2 = new User();
copyUser2.setName("赵武");
copyUser2.setAge(30);
copyUser2.setSex("女");
System.out.println(copyUser2);
BeanUtils.copyProperties(user, copyUser2,getNullPropertyNames(user));
System.out.println(copyUser2);
}
/**
* 找到source中属性值为null的属性名
* @param source
* @return
*/
public static String[] getNullPropertyNames(Object source) {
final BeanWrapper src = new BeanWrapperImpl(source);
java.beans.PropertyDescriptor[] pds = src.getPropertyDescriptors();
Set emptyNames = new HashSet();
for(java.beans.PropertyDescriptor pd : pds) {
//check if value of this property is null then add it to the collection
Object srcValue = src.getPropertyValue(pd.getName());
if (srcValue == null) {//特定字符写在此处过滤,收集不需要copy的字段列表。此处过滤null为例
emptyNames.add(pd.getName());
}
}
String[] result = new String[emptyNames.size()];
return (String[]) emptyNames.toArray(result);
}
}
class User {
private String name;
private String sex;
private Integer age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
@Override
public String toString() {
return "User{" +
"name='" + name + '\'' +
", sex='" + sex + '\'' +
", age=" + age +
'}';
}
}