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;
}
相关推荐
wind100328 分钟前
Qt5Widgets.dll 缺失报错|游戏软件无法启动完整修复教程
开发语言·qt·游戏·电脑
我叫张土豆18 分钟前
在 OpenClaw Java 对话框输入一句话后,系统是如何运行的?
java·开发语言·人工智能
liangbo725 分钟前
JVM规范第 4 章:class 文件格式
java·jvm
橘子汽水16826 分钟前
Leetcode 236,437:二叉树的最近公共祖先,路径总和III
java·数据结构
牛油果子哥q27 分钟前
C++模板万字深度精讲:函数/类模板特化、全特化与偏特化、SFINAE机制、类型萃取、模板元编程入门、工程实战落地
开发语言·c++·面试
数据狐(Datafox)33 分钟前
1688商品详情API技术解析与落地应用(含标准 JSON 示例)
java·数据库·json
神仙别闹41 分钟前
基于C++ 实现 L 系统分形树
开发语言·c++
君顾141 分钟前
AI智能商城实战指南:从架构设计到部署落地的完整技术方案
java·开发语言·多商户
Rain的Java大神之路43 分钟前
SkyWalking从0-1部署成功实战
java·后端·架构
就叫飞六吧44 分钟前
Spring 动态注册与移除 Bean 科普
java·后端·spring