BeanUtils.copyProperties()备忘以及覆盖值问题
内容纲要

BeanUtils.copyProperties会进行类型转换;
BeanUtils.copyProperties方法简单来说就是将两个字段相同的对象进行属性值的复制。如果 两个对象之间存在名称不相同的属性,则 BeanUtils 不对这些属性进行处理,需要程序手动处理。

这两个类在不同的包下面,而这两个类的copyProperties()方法里面传递的参数赋值是相反的

一、 org.springframework.beans.BeanUtils

a拷贝到b (推荐使用spring的)

a,b为对象
BeanUtils.copyProperties(a, b);

二、org.apache.commons.beanutils.BeanUtils

b拷贝到a

a,b为对象
BeanUtils.copyProperties(a, b);

Demo

import org.springframework.beans.BeanUtils;

public SysUserEnvConf updateConf(SysUserEnvConf userEnvConf) {
    SysUserEnvConf originConf = this.getById(userEnvConf.getId());
    //将 userEnvConf 覆盖拷贝到 originConf ,并排除无值的字段
    BeanUtils.copyProperties(userEnvConf, originConf, getNullPropertyNames(userEnvConf));
    this.updateById(originConf);
    return this.fetchConfDetail();
}

由于BeanUtils.copyProperties()方法会将目标对象(target/dest)全部拷贝到被copy的对象(source/orig)原有数据会被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);
    }

演示

BeanUtils.copyProperties(student3,teacher3,getNullPropertyNames(student3));

图解

file

本方法在引用类型null值覆盖基础上增加了基本类型的情况

hi,我是秋田猫,很高兴认识你,或许我们可以相互分享各自领域的”宝藏“,祝你天天开心~
暂无评论

发送评论 编辑评论


				
|´・ω・)ノ
ヾ(≧∇≦*)ゝ
(☆ω☆)
(╯‵□′)╯︵┴─┴
 ̄﹃ ̄
(/ω\)
∠( ᐛ 」∠)_
(๑•̀ㅁ•́ฅ)
→_→
୧(๑•̀⌄•́๑)૭
٩(ˊᗜˋ*)و
(ノ°ο°)ノ
(´இ皿இ`)
⌇●﹏●⌇
(ฅ´ω`ฅ)
(╯°A°)╯︵○○○
φ( ̄∇ ̄o)
ヾ(´・ ・`。)ノ"
( ง ᵒ̌皿ᵒ̌)ง⁼³₌₃
(ó﹏ò。)
Σ(っ °Д °;)っ
( ,,´・ω・)ノ"(´っω・`。)
╮(╯▽╰)╭
o(*////▽////*)q
>﹏<
( ๑´•ω•) "(ㆆᴗㆆ)
😂
😀
😅
😊
🙂
🙃
😌
😍
😘
😜
😝
😏
😒
🙄
😳
😡
😔
😫
😱
😭
💩
👻
🙌
🖕
👍
👫
👬
👭
🌚
🌝
🙈
💊
😶
🙏
🍦
🍉
😣
Source: github.com/k4yt3x/flowerhd
颜文字
Emoji
小恐龙
花!
上一篇
下一篇