我有两个对象 A a
和B b
:
A a = new A();
B b = new B();
我需要复制a
进入b
但是当我在a
中设置一些属性时,我仍然在 b
中得到相同的结果克隆之后。例如:
C c = new C();
c.setName("c name");
a.setAtt1("toto");
a.setAtt2("toto");
a.setAttC(c);
BeanUtils.copyproperties(a,b);
a.setAttC(null);
当我显示b
时我发现AttC
对象是null
比如在设置之前处理了副本null
在a
.
您知道如何在复制后隔离两个对象吗?
最佳答案
由于您将属性从 a 复制到 b,因此两个对象中对 c 的引用保持相同。您需要执行深度复制,将对象 c 克隆到 b 中。详情请引用以下链接: https://commons.apache.org/proper/commons-lang/javadocs/api-release/org/apache/commons/lang3/SerializationUtils.html#clone(T)
关于java - 复制后隔离JAVA中的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49796437/