<p>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? </p>

[{'answer_id': 64066, 'author': 'Jason Cohen', 'author_id': 4926, 'author_profile': 'https://Stackoverflow.com/users/4926', 'pm_score': 9, 'selected': True, 'text': '<p>A safe way is to serialize the object, then deserialize.  This ensures everything is a brand new reference.</p>\n<p><a href="http://javatechniques.com/blog/low-memory-deep-copy-technique-for-java-objects/" rel="noreferrer">Here\'s an article</a> about how to do this efficiently.</p>\n<p>Caveats: It\'s possible for classes to override serialization such that new instances are <em>not</em> created, e.g. for singletons.  Also this of course doesn\'t work if your classes aren\'t Serializable.</p>\n'}, {'answer_id': 64082, 'author': 'Orion Adrian', 'author_id': 7756, 'author_profile': 'https://Stackoverflow.com/users/7756', 'pm_score': 3, 'selected': False, 'text': "<p>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.</p>\n"}, {'answer_id': 64611, 'author': 'user8690', 'author_id': 8690, 'author_profile': 'https://Stackoverflow.com/users/8690', 'pm_score': 6, 'selected': False, 'text': '<p>You can do a serialization-based deep clone using <a href="https://commons.apache.org/proper/commons-lang/javadocs/api-release/org/apache/commons/lang3/SerializationUtils.html#clone(T)" rel="noreferrer"><code>org.apache.commons.lang3.SerializationUtils.clone(T)</code></a> in Apache Commons Lang, but be careful—the performance is abysmal.</p>\n\n<p>In general, it is best practice to write your own clone methods for each class of an object in the object graph needing cloning.  </p>\n'}, {'answer_id': 69534, 'author': 'Adisesha', 'author_id': 11092, 'author_profile': 'https://Stackoverflow.com/users/11092', 'pm_score': 3, 'selected': False, 'text': '<p>Use XStream(<a href="http://x-stream.github.io/" rel="nofollow noreferrer">http://x-stream.github.io/</a>). You can even control which properties you can ignore through annotations or explicitly specifying the property name to XStream class. Moreover you do not need to implement clonable interface. </p>\n'}, {'answer_id': 228900, 'author': 'sankara', 'author_id': 8286, 'author_profile': 'https://Stackoverflow.com/users/8286', 'pm_score': 3, 'selected': False, 'text': '<p>XStream is really useful in such instances. Here is a simple code to do cloning</p>\n\n<pre><code>private static final XStream XSTREAM = new XStream();\n...\n\nObject newObject = XSTREAM.fromXML(XSTREAM.toXML(obj));\n</code></pre>\n'}, {'answer_id': 354504, 'author': 'Julien Chastang', 'author_id': 32174, 'author_profile': 'https://Stackoverflow.com/users/32174', 'pm_score': 6, 'selected': False, 'text': '<p>A few people have mentioned using or overriding <code>Object.clone()</code>. Don\'t do it. <code>Object.clone()</code> has some major problems, and its use is discouraged in most cases. Please see Item 11, from "<a href="http://java.sun.com/docs/books/effective/" rel="noreferrer">Effective Java</a>" by Joshua Bloch for a complete answer. I believe you can safely use <code>Object.clone()</code> on primitive type arrays, but apart from that you need to be judicious about properly using and overriding clone. </p>\n\n<p>The schemes that rely on serialization (XML or otherwise) are kludgy.</p>\n\n<p>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. <code>String</code>s) do not need to be copied. As an aside, you should favor immutability for this reason.</p>\n'}, {'answer_id': 7432044, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 3, 'selected': False, 'text': '<pre><code>import com.thoughtworks.xstream.XStream;\n\npublic class deepCopy {\n    private static  XStream xstream = new XStream();\n\n    //serialize with Xstream them deserialize ...\n    public static Object deepCopy(Object obj){\n        return xstream.fromXML(xstream.toXML(obj));\n    }\n}\n</code></pre>\n'}, {'answer_id': 7596565, 'author': 'Thargor', 'author_id': 970985, 'author_profile': 'https://Stackoverflow.com/users/970985', 'pm_score': 6, 'selected': False, 'text': "<p>You can make a deep copy with serialization without creating files.</p>\n<p>Your object you wish to deep copy will need to <code>implement serializable</code>.  If the class isn't final or can't be modified, extend the class and implement serializable.</p>\n<p>Convert your class to a stream of bytes:</p>\n<pre><code>ByteArrayOutputStream bos = new ByteArrayOutputStream();\nObjectOutputStream oos = new ObjectOutputStream(bos);\noos.writeObject(object);\noos.flush();\noos.close();\nbos.close();\nbyte[] byteData = bos.toByteArray();\n</code></pre>\n<p>Restore your class from a stream of bytes:</p>\n<pre><code>ByteArrayInputStream bais = new ByteArrayInputStream(byteData);\nObject object = new ObjectInputStream(bais).readObject();\n</code></pre>\n"}, {'answer_id': 7596965, 'author': 'Adriaan Koster', 'author_id': 181336, 'author_profile': 'https://Stackoverflow.com/users/181336', 'pm_score': 5, 'selected': False, 'text': "<p>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.</p>\n<p>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.</p>\n<p>Example:</p>\n<pre><code>public class Order {\n\n    private long number;\n\n    public Order() {\n    }\n\n    /**\n     * Copy constructor\n     */\n    public Order(Order source) {\n        number = source.number;\n    }\n}\n\n\npublic class Customer {\n\n    private String name;\n    private List&lt;Order&gt; orders = new ArrayList&lt;Order&gt;();\n\n    public Customer() {\n    }\n\n    /**\n     * Copy constructor\n     */\n    public Customer(Customer source) {\n        name = source.name;\n        for (Order sourceOrder : source.orders) {\n            orders.add(new Order(sourceOrder));\n        }\n    }\n\n    public String getName() {\n        return name;\n    }\n\n    public void setName(String name) {\n        this.name = name;\n    }\n}\n</code></pre>\n<p>Edit: Note that copy constructors don't take inheritance into account. For example: If you pass an OnlineOrder (a subclass of Order) to a copy constructor a regular Order instance will be created in the copy, unless you  solve this explicitly. You could use reflection to look up a copy constructor in the runtime type of the argument. But I would suggest to not go this route and look for another solution if inheritance needs to be covered in a general way.</p>\n"}, {'answer_id': 9170760, 'author': 'Ravi Chinoy', 'author_id': 660029, 'author_profile': 'https://Stackoverflow.com/users/660029', 'pm_score': 3, 'selected': False, 'text': '<p>One very easy and simple approach is to use Jackson JSON to serialize complex Java Object to JSON and read it back.</p>\n<p>From <a href="https://github.com/FasterXML/jackson-databind/#5-minute-tutorial-streaming-parser-generator" rel="nofollow noreferrer">https://github.com/FasterXML/jackson-databind/#5-minute-tutorial-streaming-parser-generator</a> :</p>\n<pre class="lang-java prettyprint-override"><code>JsonFactory f = mapper.getFactory(); // may alternatively construct directly too\n\n// First: write simple JSON output\nFile jsonFile = new File(&quot;test.json&quot;);\nJsonGenerator g = f.createGenerator(jsonFile);\n// write JSON: { &quot;message&quot; : &quot;Hello world!&quot; }\ng.writeStartObject();\ng.writeStringField(&quot;message&quot;, &quot;Hello world!&quot;);\ng.writeEndObject();\ng.close();\n\n// Second: read file back\nJsonParser p = f.createParser(jsonFile);\n\nJsonToken t = p.nextToken(); // Should be JsonToken.START_OBJECT\nt = p.nextToken(); // JsonToken.FIELD_NAME\nif ((t != JsonToken.FIELD_NAME) || !&quot;message&quot;.equals(p.getCurrentName())) {\n   // handle error\n}\nt = p.nextToken();\nif (t != JsonToken.VALUE_STRING) {\n   // similarly\n}\nString msg = p.getText();\nSystem.out.printf(&quot;My message to you is: %s!\\n&quot;, msg);\np.close();\n</code></pre>\n'}, {'answer_id': 22546839, 'author': 'CorayThan', 'author_id': 1313268, 'author_profile': 'https://Stackoverflow.com/users/1313268', 'pm_score': 5, 'selected': False, 'text': '<p>You can <a href="https://github.com/kostaskougios/cloning" rel="noreferrer">use a library</a> that has a simple API, and performs relatively fast cloning with reflection (should be faster than serialization methods).</p>\n\n<pre><code>Cloner cloner = new Cloner();\n\nMyClass clone = cloner.deepClone(o);\n// clone is a deep-clone of o\n</code></pre>\n'}, {'answer_id': 26416825, 'author': 'supernova', 'author_id': 538160, 'author_profile': 'https://Stackoverflow.com/users/538160', 'pm_score': 2, 'selected': False, 'text': '<p>I used <a href="https://github.com/DozerMapper/dozer" rel="nofollow noreferrer">Dozer</a> for cloning java objects and it\'s great at that , <a href="https://github.com/EsotericSoftware/kryo" rel="nofollow noreferrer">Kryo</a> library is another great alternative.</p>\n'}, {'answer_id': 28195274, 'author': 'TheByeByeMan', 'author_id': 3437443, 'author_profile': 'https://Stackoverflow.com/users/3437443', 'pm_score': 4, 'selected': False, 'text': '<p>Apache commons offers a fast way to deep clone an object.</p>\n\n<pre><code>My_Object object2= org.apache.commons.lang.SerializationUtils.clone(object1);\n</code></pre>\n'}, {'answer_id': 35429885, 'author': 'Alfergon', 'author_id': 1308202, 'author_profile': 'https://Stackoverflow.com/users/1308202', 'pm_score': 2, 'selected': False, 'text': '<p><a href="http://commons.apache.org/proper/commons-beanutils/" rel="nofollow">BeanUtils</a> does a really good job deep cloning beans.</p>\n\n<pre><code>BeanUtils.cloneBean(obj);\n</code></pre>\n'}, {'answer_id': 40550518, 'author': 'Arun', 'author_id': 3278943, 'author_profile': 'https://Stackoverflow.com/users/3278943', 'pm_score': 1, 'selected': False, 'text': '<p>1)</p>\n\n<pre><code>public static Object deepClone(Object object) {\n   try {\n     ByteArrayOutputStream baos = new ByteArrayOutputStream();\n     ObjectOutputStream oos = new ObjectOutputStream(baos);\n     oos.writeObject(object);\n     ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());\n     ObjectInputStream ois = new ObjectInputStream(bais);\n     return ois.readObject();\n   }\n   catch (Exception e) {\n     e.printStackTrace();\n     return null;\n   }\n }\n\n2)\n\n    // (1) create a MyPerson object named Al\n    MyAddress address = new MyAddress("Vishrantwadi ", "Pune", "India");\n    MyPerson al = new MyPerson("Al", "Arun", address);\n\n    // (2) make a deep clone of Al\n    MyPerson neighbor = (MyPerson)deepClone(al);\n</code></pre>\n\n<p>Here your MyPerson and MyAddress class must implement serilazable interface</p>\n'}, {'answer_id': 40859968, 'author': 'tiboo', 'author_id': 280041, 'author_profile': 'https://Stackoverflow.com/users/280041', 'pm_score': 4, 'selected': False, 'text': '<p>For complicated objects and when performance is not significant i use a json library, like <a href="https://github.com/google/gson" rel="noreferrer">gson</a>\nto serialize the object to json text, then deserialize the text to get new object.</p>\n\n<p>gson which based on reflection will works in most cases, except that <code>transient</code> fields will not be copied and objects with circular reference with cause <code>StackOverflowError</code>.</p>\n\n<pre><code>public static &lt;T&gt; T copy(T anObject, Class&lt;T&gt; classInfo) {\n    Gson gson = new GsonBuilder().create();\n    String text = gson.toJson(anObject);\n    T newObject = gson.fromJson(text, classInfo);\n    return newObject;\n}\npublic static void main(String[] args) {\n    String originalObject = "hello";\n    String copiedObject = copy(originalObject, String.class);\n}\n</code></pre>\n'}, {'answer_id': 45201944, 'author': 'Ihor Rybak', 'author_id': 5810648, 'author_profile': 'https://Stackoverflow.com/users/5810648', 'pm_score': 4, 'selected': False, 'text': '<p>For <strong>Spring Framework</strong> users. Using class <code>org.springframework.util.SerializationUtils</code>:</p>\n\n<pre><code>@SuppressWarnings("unchecked")\npublic static &lt;T extends Serializable&gt; T clone(T object) {\n     return (T) SerializationUtils.deserialize(SerializationUtils.serialize(object));\n}\n</code></pre>\n'}, {'answer_id': 58967446, 'author': 'Karthik Rao', 'author_id': 2164335, 'author_profile': 'https://Stackoverflow.com/users/2164335', 'pm_score': 3, 'selected': False, 'text': '<p>Using Jackson to serialize and deserialize the object. This implementation does not require the object to implement the Serializable class.</p>\n\n<pre><code>  &lt;T&gt; T clone(T object, Class&lt;T&gt; clazzType) throws IOException {\n\n    final ObjectMapper objMapper = new ObjectMapper();\n    String jsonStr= objMapper.writeValueAsString(object);\n\n    return objMapper.readValue(jsonStr, clazzType);\n\n  }\n</code></pre>\n'}, {'answer_id': 63640212, 'author': 'mastercool', 'author_id': 9604444, 'author_profile': 'https://Stackoverflow.com/users/9604444', 'pm_score': 0, 'selected': False, 'text': '<p>Here is an easy example on how to deep clone any object:\nImplement serializable first</p>\n<pre><code>public class CSVTable implements Serializable{\n    Table&lt;Integer, Integer, String&gt; table; \n    public CSVTable() {\n        this.table = HashBasedTable.create();\n    }\n    \n    public CSVTable deepClone() {\n        try {\n            ByteArrayOutputStream baos = new ByteArrayOutputStream();\n            ObjectOutputStream oos = new ObjectOutputStream(baos);\n            oos.writeObject(this);\n\n            ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());\n            ObjectInputStream ois = new ObjectInputStream(bais);\n            return (CSVTable) ois.readObject();\n        } catch (IOException e) {\n            return null;\n        } catch (ClassNotFoundException e) {\n            return null;\n        }\n    }\n\n}\n</code></pre>\n<p>And then</p>\n<pre><code>CSVTable table = new CSVTable();\nCSVTable tempTable = table.deepClone();\n</code></pre>\n<p>is how you get the clone.</p>\n'}, {'answer_id': 65584955, 'author': 'Unmitigated', 'author_id': 9513184, 'author_profile': 'https://Stackoverflow.com/users/9513184', 'pm_score': 1, 'selected': False, 'text': '<p>Here is a generic deep cloning method using object serialization and deserialization with byte array streams (to avoid writing to a file).</p>\n<pre><code>import java.io.ByteArrayInputStream;\nimport java.io.ByteArrayOutputStream;\nimport java.io.IOException;\nimport java.io.ObjectInputStream;\nimport java.io.ObjectOutputStream;\nimport java.io.Serializable;\n\n@SuppressWarnings(&quot;unchecked&quot;)\npublic static &lt;T extends Serializable&gt; T deepClone(T t) {\n    try (ByteArrayOutputStream baos = new ByteArrayOutputStream();\n            ObjectOutputStream oos = new ObjectOutputStream(baos);) {\n        oos.writeObject(t);\n        byte[] bytes = baos.toByteArray();\n        try (ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(bytes))) {\n            return (T) ois.readObject();\n        }\n    } catch (IOException | ClassNotFoundException e) {\n        throw new RuntimeException(e);\n    }\n}\n</code></pre>\n'}, {'answer_id': 71735351, 'author': 'Fahad Israr', 'author_id': 9158840, 'author_profile': 'https://Stackoverflow.com/users/9158840', 'pm_score': 0, 'selected': False, 'text': '<p>A very quick and simple one-liner solution could be to use Jackson.</p>\n<p>Have a look at the example snippet :</p>\n<pre><code>ObjectMapper objectMapper = new ObjectMapper();\n\nMyClass deepCopyObject = objectMapper\n  .readValue(objectMapper.writeValueAsString(originalObject), MyClass.class);\n</code></pre>\n<p><em>In the above example : &quot;<strong>MyClass</strong>&quot; refers to the class of the object you want to be copied .</em></p>\n<ul>\n<li><strong>Explanation</strong> : We are simply trying to serialize the original object to string and then de-serialize the string back to object and thus getting a deep copy.</li>\n<li>Learn More about ObjectMapper here : <a href="https://fasterxml.github.io/jackson-databind/javadoc/2.7/com/fasterxml/jackson/databind/ObjectMapper.html" rel="nofollow noreferrer">https://fasterxml.github.io/jackson-databind/javadoc/2.7/com/fasterxml/jackson/databind/ObjectMapper.html</a></li>\n</ul>\n'}]
['https://Stackoverflow.com/questions/64036', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3885/']