Java Object Creation By Deserialization

In modern-day distributed system architecture, applications and databases are configured over geographical locations. Hence java Objects need to be transferred over the network as well.

Java object directly cannot be streamed directly, it needs to be converted to a byte stream. The conversion of states of an object into byte stream is called Serialization.
The conversion of a byte stream back into a java object is called Deserialization.

The Serialization and Deserialization process of java objects is platform-independent, ie Object Serialized on any platform can be Deserialised on a different platform.

Serialization and Deserialization process majorly used in Hibernate, RMI, JPA, EJB and JMS technologies.

package org.wesome.dsalgo.design.pattern;

import java.io.Serializable;

public class Apple implements Serializable {
    String name;

    public Apple() {
        System.out.println("Apple default constructor");
    }

    public Apple(String name) {
        System.out.println("Apple parameterized constructor");
        this.name = name;
    }
}
package org.wesome.dsalgo.design.pattern;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

public class ObjectCreation {
    public static void main(String[] args) {
        serializeObject();
        deSerializeObject();
    }

    private static void serializeObject() {
        System.out.println("ObjectCreation.serializeObject");
        Apple apple = new Apple("McIntosh");
        try {
            FileOutputStream fileOut = new FileOutputStream("Apple.ser");
            ObjectOutputStream objectOutputStream = new ObjectOutputStream(fileOut);
            objectOutputStream.writeObject(apple);
            objectOutputStream.close();
            fileOut.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static void deSerializeObject() {
        System.out.println("ObjectCreation.deSerializeObject");
        Apple apple = null;
        try {
            FileInputStream fileIn = new FileInputStream("Apple.ser");
            ObjectInputStream objectInputStream = new ObjectInputStream(fileIn);
            apple = (Apple) objectInputStream.readObject();
            objectInputStream.close();
            fileIn.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println("apple = " + apple);
        System.out.println("apple name = " + apple.name);
    }
}

 

follow us on