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;
}
相关推荐
Evand J1 分钟前
【MATLAB例程】自适应渐消扩展卡尔曼滤波(AFEKF)三维雷达目标跟踪|效果已调优,附下载链接和运行结果,代码直接运行即可
开发语言·算法·matlab·目标跟踪·卡尔曼滤波·自适应滤波·代码定制
爱装代码的小瓶子2 分钟前
3. 设计buffer模块
linux·服务器·开发语言·c++·php
郝学胜-神的一滴3 分钟前
Qt 高级开发 027: QTabWidget自定义样式表美化实战
开发语言·c++·qt·程序人生·软件构建·用户界面
keykey6.3 分钟前
迁移学习实战:用预训练模型做图像分类
开发语言·人工智能·深度学习·机器学习
双河子思4 分钟前
《代码整洁之道》——读书笔记(持续更新)
开发语言·c++·c#
川冰ICE4 分钟前
JavaScript实战②|电商网站交互效果,轮播图与购物车
开发语言·javascript·交互
listhi5206 分钟前
基于 Qt 5.8.0 的串口调试助手
开发语言·qt
sugar__salt16 分钟前
Bun 新一代 JavaScript/TypeScript 运行时:从入门到实战
开发语言·javascript·typescript
无心水16 分钟前
【OpenClaw:赚钱】案例19、内容产量5倍、广告收入翻4倍:播客转多平台内容矩阵全自动化实战(OpenAI Whisper + Claude)
java·人工智能·python·ai编程·openclaw·养龙虾·java.time
geovindu22 分钟前
go: Broadcast Pattern
开发语言·后端·设计模式·golang·广播模式