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;
}
相关推荐
csbysj20201 小时前
PHP Mail - 发送邮件的最佳实践指南
开发语言
我命由我123451 小时前
Android多进程开发 - AIDL 最简单的实现、传递数据大小限制
android·java·java-ee·kotlin·android studio·android jetpack·android-studio
jdbcaaa1 小时前
Go 语言 runtime 包的使用与注意事项
开发语言·后端·golang·runtime
ZHOUPUYU3 小时前
PHP 8.3网关优化:我用JIT将QPS提升300%的真实踩坑录
开发语言·php
寻寻觅觅☆7 小时前
东华OJ-基础题-106-大整数相加(C++)
开发语言·c++·算法
l1t8 小时前
在wsl的python 3.14.3容器中使用databend包
开发语言·数据库·python·databend
青云计划8 小时前
知光项目知文发布模块
java·后端·spring·mybatis
赶路人儿8 小时前
Jsoniter(java版本)使用介绍
java·开发语言
ceclar1239 小时前
C++使用format
开发语言·c++·算法
探路者继续奋斗9 小时前
IDD意图驱动开发之意图规格说明书
java·规格说明书·开发规范·意图驱动开发·idd