Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make deep copy of java object without using serialization ?

Tags:

java

deep-copy

Is it possible to make a deep copy/clone of a Java object without using serialization ? If so then how ?

like image 883
adn.911 Avatar asked Aug 24 '14 13:08

adn.911


People also ask

How can we achieve the deep cloning of an object?

To achieve a deep copy, we can serialize an object and then deserialize it to a new object.

Is Java clone a deep copy?

clone() is indeed a shallow copy. However, it's designed to throw a CloneNotSupportedException unless your object implements Cloneable . And when you implement Cloneable , you should override clone() to make it do a deep copy, by calling clone() on all fields that are themselves cloneable.

How can we make copy of a Java object?

Clone() method in Java. Object cloning refers to the creation of an exact copy of an object. It creates a new instance of the class of the current object and initializes all its fields with exactly the contents of the corresponding fields of this object.


1 Answers

You could use the Java Deep-Cloning Library to make deep copies of objects. It is really useful when you can't (or don't want) to make your classes serializable. The use is straight-forward:

Cloner cloner = new Cloner();

MyClass clone = cloner.deepClone(o);
// clone is a deep-clone of o
like image 166
enrico.bacis Avatar answered Sep 21 '22 10:09

enrico.bacis