java 属性复制为空属性不复制

工具类

java 复制代码
package com.jiayou.peis.common.core.util;

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 extends org.springframework.beans.BeanUtils{

    private static String[] getNullPropertyNames (Object source) {
        final BeanWrapper src = new BeanWrapperImpl(source);
        java.beans.PropertyDescriptor[] pds = src.getPropertyDescriptors();

        Set<String> emptyNames = new HashSet<>();
        for(java.beans.PropertyDescriptor pd : pds) {
            Object srcValue = src.getPropertyValue(pd.getName());
            if (srcValue == null||"".equals(srcValue)){
                emptyNames.add(pd.getName());
            }
        }
        String[] result = new String[emptyNames.size()];
        return emptyNames.toArray(result);
    }

    /**
     *
     * 忽略null和空值
     * src:数据对象
     * target:目标对象
     * 描述:把src对象不为null和空字符串的对象赋值给target对象
     *
     * */
    public static void copyPropertiesIgnoreNull(Object src, Object target){
        BeanUtils.copyProperties(src, target, getNullPropertyNames(src));
    }

    public static void main(String[] args) {
        Student source=new Student();
        source.setName("李四");
        source.setAge(30);
        source.setSex("男");
        source.setNation(null);

        Student target=new Student();
        target.setName("晓芳");
        target.setAge(20);
        target.setSex("女");
        target.setNation("苗族");

        /**属性复制为空属性不复制*/
        copyPropertiesIgnoreNull(source,target);
        System.out.println(target);

        /**复制全部属性(调用继承方法)*/
        copyProperties(source,target);
        System.out.println(target);
    }
}

Sudent.java

java 复制代码
package com.jiayou.peis.common.core.util;

import lombok.Data;

@Data
public class Student {
    private String name;
    private Integer age;
    private String sex;
    private String nation;
}
相关推荐
KingDol_MIni22 分钟前
Spring Boot 集成 T-io 实现客户端服务器通信
java·服务器·spring boot
许苑向上26 分钟前
Java八股文(下)
java·开发语言
逸Y 仙X31 分钟前
Git常见命令--助力开发
java·大数据·git·java-ee·github·idea
菜鸟一枚在这31 分钟前
深入解析设计模式之单例模式
开发语言·javascript·单例模式
独孤求败Ace35 分钟前
第44天:Web开发-JavaEE应用&反射机制&类加载器&利用链&成员变量&构造方法&抽象方法
java·开发语言
FLZJ_KL35 分钟前
【设计模式】【创建型模式】单例模式(Singleton)
java·单例模式·设计模式
CL_IN42 分钟前
企业数据集成:实现高效调拨出库自动化
java·前端·自动化
计算机-秋大田1 小时前
基于Spring Boot的农产品智慧物流系统设计与实现(LW+源码+讲解)
java·开发语言·spring boot·后端·spring·课程设计
matlabgoodboy1 小时前
Matlab代编电气仿真电力电子电机控制自动化新能源微电网储能能量
开发语言·matlab·自动化
计算机毕设指导61 小时前
基于SpringBoot的城乡商城协作系统【附源码】
java·spring boot·后端·mysql·spring·tomcat·maven