Paul
Paul

Reputation: 3582

Java: How to deeply clone a complex hierarchy of objects easily?

Say I have a java object like (just as a simple example)

 class Town{
     Public String name;
     Public Set<Business> Businesses;
     Public Set<Person> people; 
     Public Set<House> houses; 

     //... 
 }

Houses, person, business etc being complex objects which in turn have their own objects, which have their own objects etc - some with composition and some with aggregation type relationships.

Now, I need to add a clone method to the Town class, and I have two questions:

Or do I just have to spend the time implementing 100 .clone() methods on sub objects, and sub-sub-objects etc? (Would that be more or less work than implementing serialize on all the sub objects and doing it that way?)

Upvotes: 2

Views: 1500

Answers (1)

Jake Chasan
Jake Chasan

Reputation: 6550

You have a couple of options:

  1. Implement the clone method on all of the classes which deep copy the class and all of its instance variables (this is sometimes important to do if you do not want to rely on 3rd party frameworks)
  2. Serialize the object (it could be to a text file or a string). You can do this by using the Oracle framework Serializable that has one instance var which decodes information about the object. More info here: http://docs.oracle.com/javase/tutorial/jndi/objects/serial.html
  3. Here is a 3rd Party Library that can do a deep copy of an object: https://github.com/DozerMapper/dozer

More information on Deep Copy libraries: Java deep copy library

Upvotes: 1

Related Questions