当前位置: 首页 > news >正文

BeanUtil.copyProperties的优化与使用(解决copyProperties null值覆盖问题)

BeanUtil.copyProperties的优化与使用

  • 前言
  • 一、copyProperties是什么?
  • 二、使用步骤
    • 1.引入库
    • 2.基础使用
    • 3.进阶使用
    • 4.实用场景
  • 总结


前言

BeanUtil.copyProperties的优化与使用


一、copyProperties是什么?

在java中,我们想要将一个类的值赋值给另一个类,那么就需要使用到copyProperties函数,例如BeanUtil.copyProperties(Object source, Object target)。

二、使用步骤

1.引入库

引入如下对应工具类:

//这里引入的是5.3.1版本hutool工具类<dependency><groupId>cn.hutool</groupId><artifactId>hutool-all</artifactId><version>5.3.1</version></dependency>
//在代码中注入地址
import cn.hutool.core.bean.BeanUtil;

2.基础使用

将A中一样的字段值复制给B:

Student studentA = new Student();
Student studentB = new Student();
//将A的值赋值给B
BeanUtil.copyProperties(studentA,studentB);

3.进阶使用

我们点入hutool源码,可以看到支持第三个参数填写:

	/*** 复制Bean对象属性<br>* 限制类用于限制拷贝的属性,例如一个类我只想复制其父类的一些属性,就可以将editable设置为父类** @param source           源Bean对象* @param target           目标Bean对象* @param ignoreProperties 不拷贝的的属性列表*/public static void copyProperties(Object source, Object target, String... ignoreProperties) {copyProperties(source, target, CopyOptions.create().setIgnoreProperties(ignoreProperties));}

因此可以看出,我们可以自定义不copy的字段名,例如:我不想把A中的name值赋值给B 可以按照如下写:

Student studentA = new Student();
Student studentB = new Student();
String[] strArray = new String[1];
strArray[0] = "name"; 
//将A的值赋值给B
BeanUtil.copyProperties(studentA,studentB,strArray);

4.实用场景

在业务中,比较实用的是不将对象中的null值进行覆盖,可以使用以下支持函数

    /*** 解决BeanUtils.copyProperties() 的 null值覆盖问题(基本类型的0 0.0)* @param source* @return*/public static String[] getNullPropertyNames (Object source) {final BeanWrapper src = new BeanWrapperImpl(source);PropertyDescriptor[] pds = src.getPropertyDescriptors();Set<String> emptyNames = new HashSet<String>();for(PropertyDescriptor pd : pds) {Object srcValue = src.getPropertyValue(pd.getName());if (srcValue == null || Objects.equals(srcValue,0) || Objects.equals(srcValue,0.0)) emptyNames.add(pd.getName());}String[] result = new String[emptyNames.size()];return emptyNames.toArray(result);}
Student studentA = new Student();
Student studentB = new Student();
//studentA中的null值不进行赋值
BeanUtil.copyProperties(studentA,studentB,getNullPropertyNames(studentA));

总结

欢迎讨论。

http://www.lryc.cn/news/247665.html

相关文章:

  • Redis基本操作及使用
  • python 继承父类的变量和方法
  • ubuntu22.04新机使用(换源,下载软件,安装显卡驱动,锁屏长亮)
  • 如何给shopify的网址做301跳转
  • Redis之秒杀系统
  • c++基础----new
  • Java中的mysql——面试题+答案(存储过程,外键,隔离级别,性能优化)——第23期
  • 一种新的基于物理的AlGaN/GaN HFET紧凑模型
  • uniapp基础-教程之HBuilderX基础常识篇02
  • 如何源码编译seaTunnel
  • msng病毒分析
  • Unity安装
  • 【代洋集团特惠好物:80瓦太阳能折叠包】
  • 一致性Hash算法
  • linux 下如何将/dev/nvme0n1符格式化为空盘符
  • IP地址的最后一位不可以为0或255
  • 代洋集团:太阳能智能座椅,创新能源的未来篇章
  • linux服务器安装gitlab
  • Tlog SpringBoot3.x版本无法正常打印TraceId等数据
  • 基于Spring原生框架构建原生Spring的第一个程序!
  • [个人笔记] Git的CLI笔录
  • 如何运行C/C++程序
  • HTML中input标签的23种type类型
  • 接口多态与方法多态
  • js小技巧|如何提取经过Function函数混淆了的代码
  • 【GitLab】流水线入门
  • es 中文前缀短语匹配(搜索智能补全)
  • 机器学习之决策树及随机森林
  • 用通俗的方式讲解Transformer:从Word2Vec、Seq2Seq逐步理解到GPT、BERT
  • 数据结构-01-数组