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


}
相关推荐
q***69771 分钟前
Y20030018基于Java+Springboot+mysql+jsp+layui的家政服务系统的设计与实现 源代码 文档
java·spring boot·mysql
AH_HH1 小时前
Spring Boot 4.0 发布总结:新特性、依赖变更与升级指南
java·spring boot·后端
Tadas-Gao1 小时前
Spring Boot 4.0架构革新:构建更精简、更安全、更高效的Java应用
java·spring boot·分布式·微服务·云原生·架构·系统架构
vx_bisheyuange2 小时前
基于SpringBoot的库存管理系统
java·spring boot·后端·毕业设计
你不是我我2 小时前
【Java 开发日记】有了解过 SpringBoot 的参数配置吗?
java·开发语言·spring boot
q***49452 小时前
SpringBoot Maven 项目 pom 中的 plugin 插件用法整理
spring boot·后端·maven
爱吃烤鸡翅的酸菜鱼3 小时前
Spring Boot 实现 WebSocket 实时通信:从原理到生产级实战
java·开发语言·spring boot·后端·websocket·spring
我叫张小白。8 小时前
Spring Boot拦截器详解:实现统一的JWT认证
java·spring boot·web·jwt·拦截器·interceptor
q***697711 小时前
Spring Boot与MyBatis
spring boot·后端·mybatis
r***123812 小时前
SpringBoot最佳实践之 - 使用AOP记录操作日志
java·spring boot·后端