温馨提示×

java中BeanUtils.copyProperties()怎么使用

小亿
84
2023-09-12 21:32:58
栏目: 编程语言

BeanUtils.copyProperties()方法用于将一个JavaBean对象的属性值复制到另一个JavaBean对象中。使用该方法需要引入org.apache.commons.beanutils.BeanUtils类。

使用方法如下:

  1. 引入依赖:
<dependency>
<groupId>commons-beanutils</groupId>
<artifactId>commons-beanutils</artifactId>
<version>1.9.4</version>
</dependency>
  1. 调用BeanUtils.copyProperties()方法:
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.PropertyUtils;
public class Main {
public static void main(String[] args) throws Exception {
// 创建源对象和目标对象
SourceBean sourceBean = new SourceBean();
TargetBean targetBean = new TargetBean();
// 设置源对象的属性值
sourceBean.setName("John");
sourceBean.setAge(25);
// 复制属性值
BeanUtils.copyProperties(targetBean, sourceBean);
// 打印目标对象的属性值
System.out.println(targetBean.getName());  // 输出: John
System.out.println(targetBean.getAge());   // 输出: 25
}
}
// 源对象类
class SourceBean {
private String name;
private int age;
// getter和setter方法
}
// 目标对象类
class TargetBean {
private String name;
private int age;
// getter和setter方法
}

在上面的例子中,通过调用BeanUtils.copyProperties(targetBean, sourceBean)方法,将源对象sourceBean的属性值复制到目标对象targetBean中。最后,打印目标对象的属性值,可以看到目标对象的属性值已经被复制成功。

需要注意的是,源对象和目标对象的属性名和类型要相同或兼容,否则可能会抛出异常。此外,BeanUtils.copyProperties()方法只会复制源对象中存在的属性值,如果目标对象中存在的属性值会被覆盖。如果需要复制嵌套对象的属性值,可以使用PropertyUtils.copyProperties()方法。

0