How do you make a deep copy of an object in Java?

2018-12-31 03:37发布

In java it's a bit difficult to implement a deep object copy function. What steps you take to ensure the original object and the cloned one share no reference?

标签: java class clone
17条回答
妖精总统
2楼-- · 2018-12-31 04:17

1)

public static Object deepClone(Object object) {
   try {
     ByteArrayOutputStream baos = new ByteArrayOutputStream();
     ObjectOutputStream oos = new ObjectOutputStream(baos);
     oos.writeObject(object);
     ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
     ObjectInputStream ois = new ObjectInputStream(bais);
     return ois.readObject();
   }
   catch (Exception e) {
     e.printStackTrace();
     return null;
   }
 }

2)

    // (1) create a MyPerson object named Al
    MyAddress address = new MyAddress("Vishrantwadi ", "Pune", "India");
    MyPerson al = new MyPerson("Al", "Arun", address);

    // (2) make a deep clone of Al
    MyPerson neighbor = (MyPerson)deepClone(al);

Here your MyPerson and MyAddress class must implement serilazable interface

查看更多
余生无你
3楼-- · 2018-12-31 04:18

A few people have mentioned using or overriding Object.clone(). Don't do it. Object.clone() has some major problems, and its use is discouraged in most cases. Please see Item 11, from "Effective Java" by Joshua Bloch for a complete answer. I believe you can safely use Object.clone() on primitive type arrays, but apart from that you need to be judicious about properly using and overriding clone.

The schemes that rely on serialization (XML or otherwise) are kludgy.

There is no easy answer here. If you want to deep copy an object you will have to traverse the object graph and copy each child object explicitly via the object's copy constructor or a static factory method that in turn deep copies the child object. Immutables (e.g. Strings) do not need to be copied. As an aside, you should favor immutability for this reason.

查看更多
路过你的时光
4楼-- · 2018-12-31 04:19

A safe way is to serialize the object, then deserialize. This ensures everything is a brand new reference.

Here's an article about how to do this efficiently.

Caveats: It's possible for classes to override serialization such that new instances are not created, e.g. for singletons. Also this of course doesn't work if your classes aren't Serializable.

查看更多
皆成旧梦
5楼-- · 2018-12-31 04:20

I used Dozer for cloning java objects and it's great at that , Kryo library is another great alternative.

查看更多
宁负流年不负卿
6楼-- · 2018-12-31 04:21

BeanUtils does a really good job deep cloning beans.

BeanUtils.cloneBean(obj);
查看更多
登录 后发表回答