Note that there are some explanatory texts on larger screens.

plurals
  1. POJava: recommended solution for deep cloning/copying an instance
    primarykey
    data
    text
    <p>I'm wondering if there is a recommended way of doing deep clone/copy of instance in java.</p> <p>I have 3 solutions in mind, but I can have miss some, and I'd like to have your opinion</p> <p>edit: include Bohzo propositon and refine question: it's more about deep cloning than shallow cloning.</p> <h2>Do it yourself:</h2> <p>code the clone by hand properties after properties and check that mutable instances are cloned too.<br> <strong>pro:</strong><br> - control of what will be performed<br> - quick execution<br> <strong>cons:</strong><br> - tedious to write and maintain<br> - bug prone (copy/paste failure, missing property, reassigned mutable property) </p> <h2>Use reflection:</h2> <p>With your own reflection tools or with an external helper (like jakarta common-beans) it is easy to write a generic copy method that will do the job in one line.<br> <strong>pro:</strong><br> - easy to write<br> - no maintenance<br> <strong>cons:</strong><br> - less control of what happens<br> - bug prone with mutable object if the reflection tool does not clone sub objects too<br> - slower execution</p> <h2>Use clone framework:</h2> <p>Use a framework that do it for you, like :<br> <a href="http://commons.apache.org/proper/commons-lang/javadocs/api-3.0.1/org/apache/commons/lang3/SerializationUtils.html" rel="noreferrer">commons-lang SerializationUtils</a><br> <a href="https://github.com/kostaskougios/cloning" rel="noreferrer">Java Deep Cloning Library</a><br> <a href="http://dozer.sourceforge.net/documentation/about.html" rel="noreferrer">Dozer</a><br> <a href="https://github.com/EsotericSoftware/kryo" rel="noreferrer">Kryo</a></p> <p><strong>pro:</strong><br> - same as reflection<br> - more control over what will be exactly be cloned.<br> <strong>cons:</strong><br> - every mutable instance is fully cloned, even at the end of the hierarchy<br> - could be very slow to execute</p> <h2>Use bytecode instrumentation to write clone at runtime</h2> <p><a href="http://www.jboss.org/javassist" rel="noreferrer">javassit</a>, <a href="http://jakarta.apache.org/bcel/index.html" rel="noreferrer">BCEL</a> or <a href="http://cglib.sourceforge.net/" rel="noreferrer">cglib</a> might be use to generate a dedicated cloner as fast as one hand writed. Someone knows a lib using one of these tools for this purpose ?</p> <p>What I have missed here ?<br> Which one would you recommend ?</p> <p>Thanks.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload