返回博主主页

springframework BeanUtils 复制java对象属性值 copyProperties


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);
    }
}

posted @ 2024-03-04 19:15  懒惰的星期六  阅读(27)  评论(0编辑  收藏  举报

Welcome to here

主页