BeanUtils.copyProperties方法是否支持深度复制?
时间: 2023-12-07 16:39:45 浏览: 89
根据提供的引用内容[1]和,BeanUtils.copyProperties方法不支持深度复制,它只能进行浅拷贝。这意味着,如果源对象中有一个引用类型的属性,那么目标对象中的相应属性将包含对同一对象的引用。因此,如果更改源对象中的引用类型属性,则目标对象中的相应属性也将更改。如果需要进行深度复制,可以使用其他工具类,例如Apache Commons的SerializationUtils或Spring的SerializationUtils。以下是一个使用SerializationUtils进行深度复制的示例:
```java
import org.apache.commons.lang3.SerializationUtils;
public class DeepCopyExample {
public static void main(String[] args) {
MyClass source = new MyClass();
source.setName("John");
source.setAddress(new Address("123 Main St", "Anytown", "USA"));
MyClass target = SerializationUtils.clone(source);
System.out.println("Source: " + source);
System.out.println("Target: " + target);
// Change source address
source.getAddress().setCity("New York");
System.out.println("Source: " + source);
System.out.println("Target: " + target);
}
}
class MyClass implements Serializable {
private String name;
private Address address;
// getters and setters
}
class Address implements Serializable {
private String street;
private String city;
private String country;
// getters and setters
}
```
输出:
```
Source: MyClass{name='John', address=Address{street='123 Main St', city='Anytown', country='USA'}}
Target: MyClass{name='John', address=Address{street='123 Main St', city='Anytown', country='USA'}}
Source: MyClass{name='John', address=Address{street='123 Main St', city='New York', country='USA'}}
Target: MyClass{name='John', address=Address{street='123 Main St', city='Anytown', country='USA'}}
```
阅读全文