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;
}
相关推荐
美好的事情能不能发生在我身上3 小时前
Hot100中的:贪心专题
java·数据结构·算法
myloveasuka3 小时前
Java与C++多态访问成员变量/方法 对比
java·开发语言·c++
2301_821700533 小时前
C++编译期多态实现
开发语言·c++·算法
Andya_net3 小时前
Spring | @EventListener事件机制深度解析
java·后端·spring
奥地利落榜美术生灬3 小时前
c++ 锁相关(mutex 等)
开发语言·c++
xixihaha13243 小时前
C++与FPGA协同设计
开发语言·c++·算法
lang201509283 小时前
18 Byte Buddy 进阶指南:解锁 `@Pipe` 注解,实现灵活的方法转发
java·byte buddy
重庆小透明3 小时前
【java基础篇】详解BigDecimal
java·开发语言
ID_180079054734 小时前
模拟1688商品详情的Python API实现,返回符合风格的JSON数据
开发语言·python·json
小小怪7504 小时前
C++中的函数式编程
开发语言·c++·算法