1

Possible Duplicate:
Java: recommended solution for deep cloning/copying an instance

I have an object which has to be cloned. However while cloning it should also clone the objects inside it. How is this possible ??

Community
  • 1
  • 1
Anand B
  • 2,997
  • 11
  • 34
  • 55

6 Answers6

7

You must be aware that this is not a well-defined problem and deep-copying cannot be properly done in a mechanized, fully automatic way. These are some of the options:

  • Java has the clone protocol, but it's considered deprecated for most scenarios nowadays;
  • you can use serialization to serialize-deserialize in-memory;
  • you can write so-called copy constructors.
Marko Topolnik
  • 195,646
  • 29
  • 319
  • 436
3

Java Deep-Cloning library The cloning library is a small, open source java library which deep-clones objects. The objects don't have to implement the Cloneable interface. Effectivelly, this library can clone ANY java objects.

Cloner cloner = new Cloner();
MyClass clone = cloner.deepClone(o);

So and here is example cloning.

Simon Dorociak
  • 33,374
  • 10
  • 68
  • 106
2

You need to override clone() method as such

public class Person implements Cloneable{
 private Long id;
 private Address address

  @Override
  protected Object clone() throws CloneNotSupportedException {
  //do deep cloning
  }

 }

Also See

Community
  • 1
  • 1
jmj
  • 237,923
  • 42
  • 401
  • 438
0

The simplest way to implement a deep copy is to serialize and then deserialize the object. Look up ObjectInputStream and ObjectOutputStream.

Alex D
  • 29,755
  • 7
  • 80
  • 126
0

The simplest approach to deep cloning is to use Java serialization, where you serialize and deserialize the object and return the deserialized version.

Pramod Kumar
  • 7,914
  • 5
  • 28
  • 37
  • A disadvantage of this is ofcourse that the class and everything that it refers to must be `Serializable`. – Jesper Jun 25 '12 at 11:02
0

Another way of cloning is to provide a copy constructor to construct a new instance based on the data of the provided instance:

public MyClass(MyClass instanceToCopy)
{
   ...
}
ekholm
  • 2,543
  • 18
  • 18