Skip to content

Instantly share code, notes, and snippets.

@junxy
Last active December 28, 2020 06:22
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save junxy/da05a2b11177c1a92ac430892909bbec to your computer and use it in GitHub Desktop.
Save junxy/da05a2b11177c1a92ac430892909bbec to your computer and use it in GitHub Desktop.
Bean属性复制 忽略空值/空白字符
package test;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeanWrapper;
import org.springframework.beans.BeanWrapperImpl;
import java.beans.PropertyDescriptor;
import java.util.HashSet;
import java.util.Set;
public class BeanUtils2 {
public static void copyProperties(Object source, Object target) {
BeanUtils.copyProperties(source, target, getNullOrEmptyPropertyNames(source));
}
public static String[] getNullOrEmptyPropertyNames(Object source) {
final BeanWrapper src = new BeanWrapperImpl(source);
PropertyDescriptor[] pds = src.getPropertyDescriptors();
Set<String> emptyNames = new HashSet<>();
for (PropertyDescriptor pd : pds) {
Object srcValue = src.getPropertyValue(pd.getName());
// 此处判断可根据需求修改
if (srcValue == null || StringUtils.isBlank(srcValue + "")) {
emptyNames.add(pd.getName());
}
}
String[] result = new String[emptyNames.size()];
return emptyNames.toArray(result);
}
}
@junxy
Copy link
Author

junxy commented Dec 28, 2020

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment