Deep cloning using in memory serialization in java

In demonstration program, I have created a demo class named DeepCloning. I have make use of serialization while make clone.
Whenever clone method invoked on an instance of DeepCloning, it will return exact clone/ copy of that instance.
For deep cloning, we have to first do the serialization and then deserialization.

For serialization, I have used

 ByteArrayOutputStream and ObjectOutputStream

For deserialization, I have used

ByteArrayInputStream and ObjectInputStream.

Here is the code:

package com.pract.clonning;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

public class DeepCloning implements Cloneable, Serializable {

    
    private static final long serialVersionUID = 3202891278L;
    
    private int num;
    private String name;


    public DeepCloning(int num, String name) {
        this.num = num;
        this.name = name;
    }
    
    public DeepCloning() {
    }


    @Override
    protected Object clone() throws CloneNotSupportedException {
        try {
            // write object
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream);
            objectOutputStream.writeObject(this);
            
            //read object
            ByteArrayInputStream bis = new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
            ObjectInputStream inputStream = new ObjectInputStream(bis);
            return (DeepCloning)inputStream.readObject();

        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }

        return super.clone();
    }
    
    public int getNum() {
        return num;
    }

    public void setNum(int num) {
        this.num = num;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public static void main(String[] args) throws CloneNotSupportedException {
        DeepCloning obj1 = new DeepCloning(1, "ABC");
        DeepCloning obj2 = (DeepCloning) obj1.clone();
        
        System.out.println(obj2.getName());
        obj1.setName("DEF");
        System.out.println(obj2.getName());
        
    }
}

Leave a Reply