使用 BeanUtils.copyProperties属性拷贝

配合Beanutils设置对源对象中空的元素不进行复制,避免了目标对象某属性原本不为空,赋值后为空

自定义工具类

java 复制代码
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 MyBeanUtils {

    public static void copyProperties(Object source, Object target) {
        BeanUtils.copyProperties(source, target, getNullPropertyNames(source));
    }


    /**
     * 配合Beanutils设置对源对象中空的元素不进行复制,避免了目标对象某属性原本不为空,赋值后为空
     */
    public static String[] getNullPropertyNames(Object source) {
        BeanWrapper src = new BeanWrapperImpl(source);
        java.beans.PropertyDescriptor[] pds = src.getPropertyDescriptors();

        Set<String> emptyNames = new HashSet<String>();
        for (java.beans.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);
    }


}
相关推荐
梦@_@境9 小时前
面向 Spring Boot 的可观测业务流程编排引擎
java·spring boot·后端
仙俊红11 小时前
SpringBoot启动原理
java·spring boot·后端
記億揺晃着的那天12 小时前
告别误操作!Spring Boot 多环境配置隔离与启动守卫实战
java·spring boot·后端·环境隔离
skywalker_1113 小时前
SpringBoot速通(实战教学)
java·spring boot·redis·rpc·ssm·mybatis-plus
码不停蹄的玄黓13 小时前
Spring Boot 实现过滤器(Filter)三种常用方式
java·spring boot·后端
Flittly15 小时前
【AgentScope Java新手村系列】(4)结构化输出
java·spring boot·spring·ai
kuonyuma17 小时前
MyBatis入门·注解操作
java·spring boot·mysql·spring·mybatis
我登哥MVP18 小时前
SpringCloud 核心组件解析:服务链路追踪
java·spring boot·后端·spring·spring cloud·java-ee·maven
惜缘破军19 小时前
基于 Spring Boot 3 和 Spring Cloud 2023 的微服务基础框架 hdfk7-boot
spring boot·后端·微服务