如何在 Java 中复制对象?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/869033/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 20:27:17  来源:igfitidea点击:

How do I copy an object in Java?

javaobjectcopyclone

提问by Veera

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 dumto dumtwoand change dumwithout affecting the dumtwo. But the code above is not doing that. When I change something in dum, the same change is happening in dumtwoalso.

所以,我要复制dumdumtwo和变化dum而不影响dumtwo。但是上面的代码并没有这样做。当我在 中更改某些内容时dum,也会发生相同的更改dumtwo

I guess, when I say dumtwo = dum, Java copies the reference only. So, is there any way to create a fresh copy of dumand assign it to dumtwo?

我想,当我说 时dumtwo = dum,Java复制引用。那么,有没有办法创建一个新的副本dum并将其分配给dumtwo

采纳答案by egaga

Create a copy constructor:

创建复制构造函数:

class DummyBean {
  private String dummy;

  public DummyBean(DummyBean another) {
    this.dummy = another.dummy; // you can access  
  }
}

Every object has also a clone method which can be used to copy the object, but don't use it. It's way too easy to create a class and do improper clone method. If you are going to do that, read at least what Joshua Bloch has to say about it in Effective Java.

每个对象还有一个克隆方法,可以用来复制对象,但不要使用它。创建一个类并执行不正确的克隆方法太容易了。如果您打算这样做,请至少阅读 Joshua Bloch 在Effective Java 中对此的看法。

回答by Yishai

To do that you have to clone the object in some way. Although Java has a cloning mechanism, don't use it if you don't have to. Create a copy method that does the copy work for you, and then do:

为此,您必须以某种方式克隆对象。虽然 Java 有克隆机制,但如果非必要,请不要使用它。创建一个为您完成复制工作的复制方法,然后执行以下操作:

dumtwo = dum.copy();

Hereis some more advice on different techniques for accomplishing a copy.

这里有一些关于完成副本的不同技术的更多建议。

回答by bruno conde

Yes. You need to Deep Copyyour object.

是的。您需要深度复制您的对象。

回答by Jon Bringhurst

Here's a decent explanation of clone()if you end up needing it...

clone()如果您最终需要它,这是一个体面的解释......

Here: clone (Java method)

这里:克隆(Java方法)

回答by Chrisb

Yes, you are just making a reference to the object. You can clone the object if it implements Cloneable.

是的,您只是在引用该对象。如果对象实现 ,则可以克隆该对象Cloneable

Check out this wiki article about copying objects.

查看这篇关于复制对象的 wiki 文章。

Refer here: Object copying

请参阅此处:对象复制

回答by Tom Hawtin - tackline

Other than explicitly copying, another approach is to make the object immutable (no setor other mutator methods). In this way the question never arises. Immutability becomes more difficult with larger objects, but that other side of that is that it pushes you in the direction of splitting into coherent small objects and composites.

除了显式复制之外,另一种方法是使对象不可变(无set或其他 mutator 方法)。通过这种方式,问题永远不会出现。对于较大的对象,不变性变得更加困难,但另一方面,它会将您推向分裂成连贯的小对象和组合的方向。

回答by Tom Hawtin - tackline

You can try to implement Cloneableand use the clone()method; however, if you use the clone method you should - by standard - ALWAYS override Object's public Object clone()method.

您可以尝试实现Cloneable和使用该clone()方法;但是,如果您使用 clone 方法,您应该 - 按照标​​准 - 始终覆盖Objectpublic Object clone()方法。

回答by Bhasker Tiwari

Just follow as below:

只需按照以下步骤操作:

public class Deletable implements Cloneable{

    private String str;
    public Deletable(){
    }
    public void setStr(String str){
        this.str = str;
    }
    public void display(){
        System.out.println("The String is "+str);
    }
    protected Object clone() throws CloneNotSupportedException {
        return super.clone();
    }
}

and wherever you want to get another object, simple perform cloning. e.g:

无论您想获得另一个对象,只需简单地执行克隆。例如:

Deletable del = new Deletable();
Deletable delTemp = (Deletable ) del.clone(); // this line will return you an independent
                                 // object, the changes made to this object will
                                 // not be reflected to other object

回答by Jaime Hablutzel

You can deep copy automatically with XStream, from http://x-stream.github.io/:

您可以使用 XStream 自动进行深度复制,来自http://x-stream.github.io/

XStream is a simple library to serialize objects to XML and back again.

XStream 是一个简单的库,用于将对象序列化为 XML 并再次返回。

Add it to your project (if using maven)

将它添加到您的项目中(如果使用 maven)

<dependency>
    <groupId>com.thoughtworks.xstream</groupId>
    <artifactId>xstream</artifactId>
    <version>1.3.1</version>                
</dependency>

Then

然后

DummyBean dum = new DummyBean();
dum.setDummy("foo");
DummyBean dumCopy = (DummyBean) XSTREAM.fromXML(XSTREAM.toXML(dum));

With this you have a copy without the need to implement any cloning interface.

有了这个,您就有了一个副本,而无需实现任何克隆接口。

回答by Cojones

Use a deep cloning utility:

使用深度克隆实用程序:

SomeObjectType copy = new Cloner().deepClone(someObject);

This will deep copy any java object, check it out at https://github.com/kostaskougios/cloning

这将深度复制任何 Java 对象,请在https://github.com/kostaskougios/cloning查看