Saturday, March 28, 2015

Java Object cloning

Object cloning means creating a copy of original object with different reference.

Object cloning can be of two types - Shallow cloning and Deep cloning.

Shallow cloning :-

Java Object Class already have a clone method. By default this clone method do shallow cloning.

As per java docs

Object clone method Creates and returns a copy of this object.
The precise meaning of "copy" may depend on the class of the object.
The general intent is that, for any object x, the expression:

1) x.clone() != x will be true
2) x.clone().getClass() == x.getClass() will be true, but these are not absolute requirements.
3) x.clone().equals(x) will be true, this is not an absolute requirement.



Method clone for class Object performs a specific cloning operation. if the class of this object does not implement the interface Cloneable, then a CloneNotSupportedException is thrown.

For primitive  type Member clone method create a new copy of original object with different reference, but for non primitive type member clone method only copy the reference of  member of original object. It means both original and copied member refer same non primitive object.

It means if we do any change in non primitive member of original object than it will also change the member of copied object.

Deep cloning :-


In deep cloning we create a new copy object of original object. It means copy or original object will not change by changing original or copy object.

There are many ways to do deep cloning.

1. Using a constructor :-



Employee(Employee employee){
    this.id = employee.id;
    this.name = employee.name;
}


2. Using object serializations :-



  public Object cloneObject(Object original) throws IOException, ClassNotFoundException {

        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        ObjectOutputStream out = new ObjectOutputStream(bos);
        out.writeObject(original);

        ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(
                bos.toByteArray()));
        Object clone = (PreprocessedQuery) in.readObject();
        return clone;
    }



There are some framwork available to clone java object like -
commons-lang SerializationUtils
Java Deep Cloning Library
Dozer
Kryo


You can also look stackoverflow link to get more information about java object cloning

java-recommended-solution-for-deep-cloning-copying-an-instance



1 comment: