我hava Foo和Item类如下.
import java.util.ArrayList;
import java.util.List;
public class Foo {
private Long id;
private List items;
public Foo(Long id) {
this.id = id;
this.items = new ArrayList();
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public List getItems() {
return items;
}
public void setItems(List items) {
this.items = items;
}
}
public class Item {
private String bar;
public Item(String bar) {
this.bar = bar;
}
public String getBar() {
return bar;
}
public void setBar(String bar) {
this.bar = bar;
}
@Override
public String toString() {
return "Item{" + "bar='" + bar + '\'' + '}';
}
}
当我使用spring BeanUtils复制Foo类时,列表字段的引用不会改变.
import org.springframework.beans.BeanUtils;
public class SimpleCopyMain {
public static void main(String[] args) {
Foo foo = new Foo(1L);
foo.getItems().add(new Item("item1"));
foo.getItems().add(new Item("item2"));
Foo fooSnapShot = new Foo(100L);
BeanUtils.copyProperties(foo,fooSnapShot);
foo.setId(999L);
System.out.println("fooSnapShot id field value is not changing as expected : " + fooSnapShot.getId());
foo.getItems().add(new Item("item3"));
System.out.println("fooSnapShot items value is changing unexpectedly : " + fooSnapShot.getItems());
}
}
SimpleCopyMain类的输出如下:
fooSnapShot id field value is not changing as expected : 1
fooSnapShot items value is changing unexpectedly : [Item{bar='item1'}, Item{bar='item2'}, Item{bar='item3'}]
但是,当我为列表字段创建一个新实例并逐个复制引用时,我得到了我预期的行为.
import java.util.ArrayList;
import org.springframework.beans.BeanUtils;
public class CopyMain {
public static void main(String[] args) {
Foo foo = new Foo(1L);
foo.getItems().add(new Item("item1"));
foo.getItems().add(new Item("item2"));
Foo fooSnapShot = new Foo(100L);
BeanUtils.copyProperties(foo, fooSnapShot);
fooSnapShot.setItems(new ArrayList(foo.getItems().size()));
for(int i = 0; i < foo.getItems().size(); i++){
Item anItem = new Item("");
BeanUtils.copyProperties(foo.getItems().get(i), anItem);
fooSnapShot.getItems().add(anItem);
}
foo.setId(999L);
System.out.println("fooSnapShot id field value is not changing as expected : " + fooSnapShot.getId());
foo.getItems().add(new Item("item3"));
System.out.println("fooSnapShot items value is is not changing : " + fooSnapShot.getItems());
}
}
这是输出:
fooSnapShot id field value is not changing as expected : 1
fooSnapShot items value is is not changing : [Item{bar='item1'}, Item{bar='item2'}]
而我的pom:
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
com.question
beanutils
1.0-SNAPSHOT
org.springframework
spring-beans
4.3.3.RELEASE
为什么spring beanutils没有克隆列表字段?