BeanUtils.copyProperties是深copy么
时间: 2024-01-16 17:18:45 浏览: 49
BeanUtils.copyProperties方法不是深拷贝,它是浅拷贝。浅拷贝意味着它只会复制对象的引用,而不会复制对象的内容。这意味着如果源对象的属性是引用类型,那么目标对象的属性将指向相同的引用,而不是创建一个新的对象。
以下是一个示例演示BeanUtils.copyProperties方法的使用:
```java
import org.apache.commons.beanutils.BeanUtils;
public class Main {
public static void main(String[] args) throws Exception {
Source source = new Source();
source.setName("John");
source.setAge(25);
Target target = new Target();
BeanUtils.copyProperties(target, source);
System.out.println("Source: " + source.getName() + ", " + source.getAge());
System.out.println("Target: " + target.getName() + ", " + target.getAge());
}
}
class Source {
private String name;
private int age;
// getters and setters
}
class Target {
private String name;
private int age;
// getters and setters
}
```
输出结果为:
```
Source: John, 25
Target: John, 25
```
可以看到,通过BeanUtils.copyProperties方法将源对象的属性复制到目标对象后,目标对象的属性与源对象的属性相同。这表明它们共享相同的引用,而不是创建一个新的对象。