BeanUtils只拷貝對象非null屬性

在最近做項目的時候,使用到了對象copy,而只需要拷貝源對象的非空屬性,爲null的屬性不進行吧copy。

BeanUtil.copyProperties(sourceObject,targetObject);

查了資料,解決方法如下:

1 、hutool開源庫爲我們提供了更爲強大的Bean工具-BeanUtil

引入依賴

<dependency>
    <groupId>cn.hutool</groupId>
    <artifactId>hutool-all</artifactId>
    <version>4.1.14</version>
</dependency>
//複製舊的屬性過來,忽略null屬性,忽略null值,有值的以新的爲主,null的則以舊爲主
BeanUtil.copyProperties(sourceObject, targetObject,
        true, CopyOptions.create().setIgnoreNullValue(true).setIgnoreError(true));
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章