扩展Spring BeanUtils.copyProperties方法,支持复制属性时忽略null字段

import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeansException;
import org.springframework.util.ReflectionUtils;

import java.lang.reflect.Field;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;

/**
 * 自定义Bean工具类
 * @author wrp
 * @since 2024年09月09日 11:02
 */
public class MyBeanUtils {

    /**
     * 赋值
     * @param source 源对象
     * @param target 目标对象
     * @throws BeansException
     */
    public static void copy(Object source, Object target) throws BeansException {
        BeanUtils.copyProperties(source, target);
    }

    /**
     * 赋值时忽略空字段
     * @param source 源对象
     * @param target 目标对象
     * @throws BeansException
     */
    public static void copyIgnoreNull(Object source, Object target) throws BeansException {
        BeanUtils.copyProperties(source, target, getNullFields(source));
    }

    private static String[] getNullFields(Object source) {
        List<String> nullFiledNames = new ArrayList<>();
        Class<?> type = source.getClass();
        // 包括父类继承下来的字段
        while(!type.equals(Object.class)) {
            Field[] declaredFields = type.getDeclaredFields();
            for (Field field : declaredFields) {
                ReflectionUtils.makeAccessible(field);
                try {
                    if(field.get(source) == null) {
                        nullFiledNames.add(field.getName());
                    }
                } catch (IllegalAccessException e) {
                    throw new RuntimeException(e);
                }
            }
            type = type.getSuperclass();
        }

        return nullFiledNames.toArray(new String[0]);
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值