Java: recommended solution for deep cloning/copying an instance

For deep cloning (clones the entire object hierarchy):

  • commons-lang SerializationUtils – using serialization – if all classes are in your control and you can force implementing Serializable.

  • Java Deep Cloning Library – using reflection – in cases when the classes or the objects you want to clone are out of your control (a 3rd party library) and you can’t make them implement Serializable, or in cases you don’t want to implement Serializable.

For shallow cloning (clones only the first level properties):

I deliberately omitted the “do-it-yourself” option – the API’s above provide a good control over what to and what not to clone (for example using transient, or String[] ignoreProperties), so reinventing the wheel isn’t preferred.

Leave a Comment