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;
/**
* ObjectBeanUtils
*
* @author s30047463
* @since 2024-03-01 12:20
*/
public class ObjectBeanUtils {
/**
* 当 ignoreNull 为 true, 忽略 source 中值为 null 的属性
*
* @param source 源对象
* @param target 目标对象
* @param ignoreNull 是否忽略 source 中的 null 属性
*/
public static void copyProperties(Object source, Object target, boolean ignoreNull) {
if (ignoreNull) {
BeanUtils.copyProperties(source, target, getNullPropertyNames(source));
} else {
BeanUtils.copyProperties(source, target);
}
}
private static String[] getNullPropertyNames(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) {
emptyNames.add(pd.getName());
}
}
String[] result = new String[emptyNames.size()];
return emptyNames.toArray(result);
}
}
标签:java,springframework,source,copyProperties,import,BeanUtils
From: https://www.cnblogs.com/sunupo/p/18052462