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;
}
相关推荐
庄小法1 天前
pytest
开发语言·python·pytest
sonnet-10291 天前
堆排序算法
java·c语言·开发语言·数据结构·python·算法·排序算法
csdn_zhangchunfeng1 天前
Qt之智能指针使用建议
开发语言·qt
我是咸鱼不闲呀1 天前
力扣Hot100系列24(Java)——[回溯]总结(下)(括号生成,单词搜索,分割回文串)
java·算法·leetcode
升鲜宝供应链及收银系统源代码服务1 天前
生鲜配送供应链管理系统源代码之升鲜宝社区团购商城小程序(一)
java·前端·数据库·小程序·notepad++·供应链系统源代码·多门店收银系统
2401_895521341 天前
Golang 构建学习
开发语言·学习·golang
墨香幽梦客1 天前
大数据环境下的BI架构:Hadoop与Spark的企业级应用整理
java·开发语言
2301_810160951 天前
C++中的状态模式
开发语言·c++·算法
码路星河1 天前
SpringBoot3实战:优雅实现Word文档动态生成与下载
开发语言·c#·word
AIminminHu1 天前
OpenGL渲染与几何内核那点事-项目实践理论补充(一-1-(2):看似“老派”的 C++ 底层优化,恰恰是这些前沿领域最需要的基础设施)
开发语言·c++