BeanUtils copyProperties API 忽略 null 和特定属性

spring

1个回答

写回答

柏大发

2025-06-20 07:10

+ 关注

Java
Java

使用BeanUtils的copyProperties API是一种方便快捷的方式,可以将一个Java对象的属性值复制到另一个对象中。这个API提供了许多功能和选项,其中之一是可以忽略源对象属性值为null的情况,同时还可以选择性地忽略特定的属性。

在实际开发中,我们经常需要将一个对象的属性值复制给另一个对象,特别是当两个对象的属性名和类型相同时。这个时候,使用BeanUtils的copyProperties API可以省去手动复制属性值的麻烦。

在使用copyProperties API时,我们可以通过设置BeanUtilsBean的copyProperties方法的第三个参数,即PropertyUtilsBean的ignoreNull属性,来忽略源对象属性值为null的情况。例如:

User sourceUser = new User();

sourceUser.setName("John");

sourceUser.setAge(25);

User targetUser = new User();

targetUser.setName("Tom");

targetUser.setAge(30);

BeanUtilsBean beanUtils = new BeanUtilsBean();

beanUtils.getcopyUtils().setIgnoreNull(true);

beanUtils.copyProperties(targetUser, sourceUser);

System.out.println(targetUser.getName()); // 输出结果为"John"

System.out.println(targetUser.getAge()); // 输出结果为25

在上面的例子中,源对象sourceUser的name属性值为"John",age属性值为25。目标对象targetUser的name属性值为"Tom",age属性值为30。通过设置BeanUtilsBean的ignoreNull属性为true,我们忽略了源对象的name属性值为null的情况,从而将源对象的name属性值复制到了目标对象中。

此外,BeanUtils的copyProperties API还提供了另一个选项,即通过设置exclude属性来选择性地忽略特定的属性。例如:

User sourceUser = new User();

sourceUser.setName("John");

sourceUser.setAge(25);

User targetUser = new User();

targetUser.setName("Tom");

targetUser.setAge(30);

BeanUtilsBean beanUtils = new BeanUtilsBean();

beanUtils.getcopyUtils().setExclude("age");

beanUtils.copyProperties(targetUser, sourceUser);

System.out.println(targetUser.getName()); // 输出结果为"John"

System.out.println(targetUser.getAge()); // 输出结果为30

在上面的例子中,通过设置BeanUtilsBean的exclude属性为"age",我们选择性地忽略了源对象的age属性。因此,只有name属性值被复制到了目标对象中,而age属性值保持不变。

可以忽略null和特定属性的案例代码

Java

public class User {

private String name;

private Integer age;

// 省略getter和setter方法

}

public class MAIn {

public static void mAIn(String[] args) throws Exception {

User sourceUser = new User();

sourceUser.setName("John");

sourceUser.setAge(25);

User targetUser = new User();

targetUser.setName("Tom");

targetUser.setAge(30);

BeanUtilsBean beanUtils = new BeanUtilsBean();

beanUtils.getcopyUtils().setIgnoreNull(true);

beanUtils.getcopyUtils().setExclude("age");

beanUtils.copyProperties(targetUser, sourceUser);

System.out.println(targetUser.getName()); // 输出结果为"John"

System.out.println(targetUser.getAge()); // 输出结果为30

}

}

使用BeanUtils的copyProperties API可以方便地将一个Java对象的属性值复制到另一个对象中。通过设置ignoreNull属性,我们可以忽略源对象属性值为null的情况;通过设置exclude属性,我们可以选择性地忽略特定的属性。这些功能使得属性复制变得更加灵活和便捷。在实际开发中,合理使用copyProperties API可以提高代码的效率和可读性。

举报有用(4分享收藏

Copyright © 2025 IZhiDa.com All Rights Reserved.

知答 版权所有 粤ICP备2023042255号