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


}
相关推荐
h***593329 分钟前
SpringBoot中如何手动开启事务
java·spring boot·spring
q_191328469530 分钟前
基于SpringBoot2+Vue2的宠物健康医疗论坛系统
vue.js·spring boot·mysql·健康医疗·宠物·计算机毕业设计
L.EscaRC1 小时前
深入解析SpringBoot中的循环依赖机制与解决方案
java·spring boot·spring·循环依赖
q***48411 小时前
SpringBoot整合easy-es
spring boot·后端·elasticsearch
一 乐2 小时前
健身达人小程序|基于java+vue健身达人小程序的系统设计与实现(源码+数据库+文档)
java·前端·数据库·vue.js·spring boot·小程序
倚肆2 小时前
Spring Boot 中的 Bean 与自动装配详解
spring boot·后端·python
g***96903 小时前
【Spring Boot 实现 PDF 导出】
spring boot·后端·pdf
k***3885 小时前
SpringBoot Test详解
spring boot·后端·log4j
z***89716 小时前
SpringBoot Maven 项目 pom 中的 plugin 插件用法整理
spring boot·后端·maven
j***63089 小时前
Springboot项目中线程池使用整理
java·spring boot·后端