如何在Java中复制对象?

时光毁灭记忆、已成空白 提交于 2020-04-25 16:01:07

问题:

Consider the code below: 考虑下面的代码:

DummyBean dum = new DummyBean();
dum.setDummy("foo");
System.out.println(dum.getDummy()); // prints 'foo'

DummyBean dumtwo = dum;
System.out.println(dumtwo.getDummy()); // prints 'foo'

dum.setDummy("bar");
System.out.println(dumtwo.getDummy()); // prints 'bar' but it should print 'foo'

So, I want to copy the dum to dumtwo and change dum without affecting the dumtwo . 因此,我想将dum复制到dumtwo并在不影响dumtwo情况下更改dum But the code above is not doing that. 但是上面的代码没有这样做。 When I change something in dum , the same change is happening in dumtwo also. 当我改变的东西dum ,同一个变化在发生dumtwo也。

I guess, when I say dumtwo = dum , Java copies the reference only . 我猜想,当我说dumtwo = dum ,Java 复制引用 So, is there any way to create a fresh copy of dum and assign it to dumtwo ? 那么,有什么方法可以创建新的dum副本并将其分配给dumtwo吗?


解决方案:

参考一: https://stackoom.com/question/3e4f/如何在Java中复制对象
参考二: https://oldbug.net/q/3e4f/How-do-I-copy-an-object-in-Java
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!