Easiest way of deep cloning (with some performance overhead) is Serialization. It involves serializing the object to bytes and from bytes to object again.
We should prefer to use in memory deep cloning whenever it is the only need and we don’t need to persist the object for future use.
For deep cloning, we have to first serialization and then deserialization. For serialization, I have used ByteArrayOutputStream and ObjectOutputStream. For deserialization, I have used ByteArrayInputStream and ObjectInputStream.
Steps:
1. Ensure that all classes in the object's graph are serializable.
2. Create input and output streams.
3. Use the input and output streams to create object input and object output streams.
4. Pass the object that you want to copy to the object output stream.
5. Read the new object from the object input stream and cast it back to the class of the object you sent.
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
public class DeepCopySerializable implements Serializable{
private static final long serialVersionUID = 1L;
private String name = null;
private String company = null;
@SuppressWarnings("serial")
private List<String> permissions = new ArrayList<String>()
{ { add("Software engg."); add("Java Tech."); }};
public DeepCopySerializable(final String empName,
final String company) {
this.name = empName;
this.company = company;
}
public DeepCopySerializable deepCopy() throws Exception {
//Serialization of object
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream out = new ObjectOutputStream(bos);
out.writeObject(this);
//De-serialization of object
ByteArrayInputStream bis=
new ByteArrayInputStream(bos.toByteArray());
ObjectInputStream in = new ObjectInputStream(bis);
DeepCopySerializable copied =
(DeepCopySerializable) in.readObject();
return copied;
}
//setters and getters
@Override
public String toString() {
return new StringBuilder().append(getName()+",")
.append(getCompany()+",")
.append(permissions)
.toString();
}
}
public class DeepCopySerializableTest {
public static void main(String[] args) throws Exception {
//Create instance of serializable object
DeepCopySerializable serializable =
new DeepCopySerializable("Rajesh","Ornage");
//Verify the content
System.out.println(serializable);
//Now create a deep copy of it
DeepCopySerializable deepCopiedInstance =
serializable.deepCopy();
//Again verify the content
System.out.println(deepCopiedInstance);
}
}
Output:
Rajesh,Ornage,[Software engg., Java Tech.]
Rajesh,Ornage,[Software engg., Java Tech.]
No comments:
Post a Comment