Rectangle 27 1

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


import com.thoughtworks.xstream.XStream;

public class deepCopy {
    private static  XStream xstream = new XStream();

    //serialize with Xstream them deserialize ...
    public static Object deepCopy(Object obj){
        return xstream.fromXML(xstream.toXML(obj));
    }
}
Note
Rectangle 27 1

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


Deep copying can only be done with each class's consent. If you have control over the class hierarchy then you can implement the clonable interface and implement the Clone method. Otherwise doing a deep copy is impossible to do safely because the object may also be sharing non-data resources (e.g. database connections). In general however deep copying is considered bad practice in the Java environment and should be avoided via the appropriate design practices.

Note
Rectangle 27 1

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


Could you describe the "appropriate design practices"?

Deep copying can only be done with each class's consent. If you have control over the class hierarchy then you can implement the clonable interface and implement the Clone method. Otherwise doing a deep copy is impossible to do safely because the object may also be sharing non-data resources (e.g. database connections). In general however deep copying is considered bad practice in the Java environment and should be avoided via the appropriate design practices.

Note
Rectangle 27 1

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


Cloner cloner = new Cloner();

MyClass clone = cloner.deepClone(o);
// clone is a deep-clone of o

You can use a library that has a simple API, and performs relatively fast cloning with reflection (should be faster than serialization methods).

Note
Rectangle 27 1

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


ByteArrayInputStream bais = new ByteArrayInputStream(byteData);
(Object) object = (Object) new ObjectInputStream(bais).readObject();
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(bos);
oos.writeObject(object);
oos.flush();
oos.close();
bos.close();
byte[] byteData = bos.toByteArray();

Convert your class to a stream of bytes:

If the class is final how would you extend it?

Restore your class from a stream of bytes:

You can make a deep copy with serialization without creating files.

Your object you wish to deep copy will need to implement serializable. If the class isn't final or can't be modified, extend the class and implement serializable.

Note
Rectangle 27 1

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


My_Object object2= org.apache.commons.lang.SerializationUtils.clone(object1);

Apache commons offers a fast way to deep clone an object.

upvote for suggesting a tested and stable library

Note
Rectangle 27 1

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


Sign up for our newsletter and get our top new questions delivered to your inbox (see an example).

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

Be aware that the FastByteArrayOutputStream implementation provided in the article could be more efficient. It uses an ArrayList-style expansion when the buffer fills up, but it's better to use a LinkedList-style expansion approach. Instead of creating a new 2x buffer and memcpy-ing the current buffer over, maintain a linked list of buffers, adding a new one when the current fills up. If you get a request to write more data than would fit in your default buffer size, create a buffer node that is exactly as large as the request; the nodes don't need to be the same size.

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.

Note
Rectangle 27 1

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


One very easy and simple approach is to use Jackson JSON to serialize complex Java Object to JSON and read it back.

Note
Rectangle 27 1

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


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.

Note
Rectangle 27 1

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


public class Order {

    private long number;

    public Order() {
    }

    /**
     * Copy constructor
     */
    public Order(Order source) {
        number = source.number;
    }
}


public class Customer {

    private String name;
    private List<Order> orders = new ArrayList<Order>();

    public Customer() {
    }

    /**
     * Copy constructor
     */
    public Customer(Customer source) {
        name = source.name;
        for (Order sourceOrder : source.orders) {
            orders.add(new Order(sourceOrder));
        }
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

@AdriaanKoster: If the original list contains a Toyota, your code will put a Car in the destination list. Proper cloning generally requires that the class provide a virtual factory method whose contract states that it will return a new object of its own class; the copy contructor itself should be protected to ensure that it will only be used to construct objects whose precise type matches that of the object being copied).

EDIT: note that you don't need to use accessor methods to read fields. You can access all fields directly because the source instance is always of the same type as the instance with the copy constructor. Obvious but might be overlooked.

Edit: Note that when using copy constructors you need to know the runtime type of the object you are copying. With the above approach you cannot easily copy a mixed list (you might be able to do it with some reflection code).

Just interested in the case that what you are copying is a subclass, but is being referenced by the parent. Is it possible to override the copy constructor?

One way to implement deep copy is to add copy constructors to each associated class. A copy constructor takes an instance of 'this' as its single argument and copies all the values from it. Quite some work, but pretty straightforward and safe.

public class Car extends Vehicle And then referring to the car as a vehicle. originaList = new ArrayList<Vehicle>; copyList = new ArrayList<Vehicle>; originalList.add(new Car()); for(Vehicle vehicle: vehicleList){ copyList.add(new Vehicle(vehicle)); }

Note