BeanUtils.copyProperties()的用法
时间: 2024-04-30 13:16:07 浏览: 7
BeanUtils.copyProperties()是Apache Commons BeanUtils库中的一个方法,用于将一个Java对象的属性值复制到另一个Java对象中。它提供了一种简单且方便的方式来实现对象之间的属性复制。
使用BeanUtils.copyProperties()方法,你需要传入两个参数:目标对象和源对象。该方法会将源对象的属性值复制到目标对象中,属性名相同的属性会被复制。
以下是BeanUtils.copyProperties()方法的用法示例:
```java
// 导入BeanUtils类
import org.apache.commons.beanutils.BeanUtils;
// 创建目标对象和源对象
User sourceUser = new User("John", 25);
User targetUser = new User();
// 使用BeanUtils.copyProperties()方法进行属性复制
BeanUtils.copyProperties(targetUser, sourceUser);
// 输出目标对象的属性值
System.out.println(targetUser.getName()); // 输出:John
System.out.println(targetUser.getAge()); // 输出:25
```
在上面的示例中,我们创建了一个源对象sourceUser和一个空的目标对象targetUser。通过调用BeanUtils.copyProperties()方法,将sourceUser的属性值复制到targetUser中。最后,我们输出了targetUser的属性值,可以看到属性值已经成功复制。