Monday, June 1, 2020

serialization and specialization

  • Object serialization is the process of converting an object into a series of bytes so they can be written to disk
  • Object to Disk (Serialization)
  • Disk to Object (Deserialization)
  • FileInputStream -used to read a file, treating it as bytes instead of text
  • FileOutputStream - used to write to a file 
  • when a method throws an exception you must either:
  1. Handle it with a surrounding try catch block
  2. Specify the main method might throw an exception when called


Serialization Example:
Serializable make the class eligible to write into the file. This is important until you have data base. The serializable is a marker interface, which marks that your class is serializable. If you want to send your data partially, then use the keyword "transient". 

Emp class:
package com.cerotid.fundamentals;

import java.io.Serializable;

public class Emp implements Serializable{
/**
     *
     */
    private static final long serialVersionUID = -4349728222760794528L;
public String name;
public String address;
@Override
public String toString() {
    return "Emp [name=" + name + ", address=" + address + "]";
}

}

Serialization:
package com.cerotid.fundamentals;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;

public class SerializationClass {

    public static void main(String[] args) {
        Emp emp = new Emp();
        emp.name = "Ram";
        emp.address = "NorthCarolina";

        try {
            FileOutputStream fileout = new FileOutputStream("txt.ser");
            ObjectOutputStream out = new ObjectOutputStream(fileout);
            out.writeObject(emp);
            out.close();
            fileout.close();
            System.out.println("serialization data is saved");
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

Deserialization of Emp Class:
package com.cerotid.fundamentals;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.ObjectInputStream;

public class DeserializationClass {

    public static void main(String[] args) {
        Emp emp = null;

        try {
            FileInputStream fileIn = new FileInputStream("txt.ser");
            ObjectInputStream in = new ObjectInputStream(fileIn);
            emp = (Emp) in.readObject();
            in.close();
            fileIn.close();
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            System.out.println("Deserialising Employee: ");
            System.out.println("First Name of Employee: " + emp.name);
            System.out.println("Employee address is: " + emp.address);
        }
    }

    

}
From tutor:
Employee class:
package com.cerotid.concept.serialization;

import java.io.Serializable;

public class Employee implements Serializable {
    private Car car;
    /**
     *
     */
    private static final long serialVersionUID = -438193571367027852L;
    /**
     *
     */

    private  String name;
    private  String address;
    private  transient int SSN;
    private  int number;
    

    public Employee(String name, String address, int sSN, int number) {
        this.name = name;
        this.address = address;
        SSN = sSN;
        this.number = number;
    }
    
    public Employee(String name, String address, int sSN, int number, Car car) {
        this.name = name;
        this.address = address;
        SSN = sSN;
        this.number = number;
        this.car = car;
    }


    public void studentInfo() {
        System.out.println("Student Name:  " + name + " " + address);
    }


    public String getName() {
        return name;
    }


    public String getAddress() {
        return address;
    }


    public int getSSN() {
        return SSN;
    }


    public int getNumber() {
        return number;
    }
    

    public Car getCar() {
        return car;
    }

    public void setCar(Car car) {
        this.car = car;
    }

    @Override
    public String toString() {
        return "Employee [car=" + car + ", name=" + name + ", address=" + address + ", SSN=" + SSN + ", number="
                + number + "]";
    }
}

Car class:
package com.cerotid.concept.serialization;

import java.io.Serializable;

public class Car implements Serializable{
    /**
     *
     */
    private static final long serialVersionUID = -3916152464829845384L;
    /**
     *
     */
    //private static final long serialVersionUID = -3916152464829845384L;
    
    private String make;
    private String model;
    private int year;
    
    public Car(String make, String model, int year) {
        super();
        this.make = make;
        this.model = model;
        this.year = year;
    }
    public String getMake() {
        return make;
    }
    public void setMake(String make) {
        this.make = make;
    }
    public String getModel() {
        return model;
    }
    public void setModel(String model) {
        this.model = model;
    }
    public int getYear() {
        return year;
    }
    public void setYear(int year) {
        this.year = year;
    }
    @Override
    public String toString() {
        return "Car [make=" + make + ", model=" + model + ", year=" + year + "]";
    }
    
    
}

Serialize:
package com.cerotid.concept.serialization;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.NotSerializableException;
import java.io.ObjectOutputStream;

public class SerializeDriver {

    public static void main(String[] args) {
        Car car = new Car("Audi", "R8", 2017);
        
        Employee employee = new Employee("David Smith","121 Main St", 222111333, 101, car);

        try {
            FileOutputStream fileOut = new FileOutputStream("employee.ser");
            ObjectOutputStream out = new ObjectOutputStream(fileOut);
            out.writeObject(employee);
            
            //out.flush();
            out.close();
            //fileOut.flush();
            fileOut.close();
            
            
            System.out.printf("Serialized data is saved as employee.ser");
        } catch (IOException i) {
            i.printStackTrace();
        }
    }

}

Deserialize
package com.cerotid.concept.serialization;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.ObjectInputStream;

public class DeserializeDriver {

    public static void main(String[] args) {
        Employee e = null;
        try {
            FileInputStream fileIn = new FileInputStream("employee.ser");
            ObjectInputStream in = new ObjectInputStream(fileIn);
            e = (Employee) in.readObject();

            in.close();
            fileIn.close();
            
            System.out.println(e);
            /*System.out.println("Right before system exit");
            System.exit(0);*/
        }
        catch (FileNotFoundException i) {
            System.out.println("I am here");
            i.printStackTrace();
            return;
        }
        catch (IOException i) {
            System.out.println("I am here2");
            i.printStackTrace();
            return;
        }
        catch (ClassNotFoundException c) {
            System.out.println("Employee class not found");
            c.printStackTrace();
            return;
            
        }
        catch(Exception e1){
            e1.printStackTrace();
        }
        
        System.out.println(e.getCar());
    }
}
Output:
Employee [car=Car [make=Audi, model=R8, year=2017], name=David Smith, address=121 Main St, SSN=0, number=101]
Car [make=Audi, model=R8, year=2017]


Serialization and DeSerialization Demo: (most important):
    System.out.println(e.getCar());
package com.cerotid.fundamentals;

import java.io.*;

class Dog implements Serializable {
    int i = 10;
    int j = 20;
}

public class SerializeDemo {

    public static void main(String[] args) {

        Dog d1 = new Dog();

        try {
            FileOutputStream fos = new FileOutputStream("abc.ser");
            ObjectOutputStream oos = new ObjectOutputStream(fos);
            oos.writeObject(d1);
        } catch (FileNotFoundException e) {

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

            e.printStackTrace();
        }

        Dog d2 = null;
        try {
            FileInputStream fis = new FileInputStream("abc.ser");
            ObjectInputStream ois = new ObjectInputStream(fis);
            d2 = (Dog) ois.readObject();
        } catch (FileNotFoundException e) {

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

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

            e.printStackTrace();
        }
        System.out.println(d2.i + " " + d2.j);
    }

}
Example II:

package com.cerotid.fundamentals;

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

class Dog implements Serializable {
    Cat c = new Cat(); // instance variable
}

class Cat implements Serializable {
    Rat r = new Rat(); // instance variable
}

class Rat implements Serializable {
    int j = 20;
}

public class SerializeDemo2 {

    public static void main(String[] args) throws Exception {
        Dog d1 = new Dog();

        FileOutputStream fos = new FileOutputStream("abc.ser");
        ObjectOutputStream oos = new ObjectOutputStream(fos);
        oos.writeObject(d1);

        FileInputStream fis = new FileInputStream("abc.ser");
        ObjectInputStream ois = new ObjectInputStream(fis);
        Dog d2 = (Dog) ois.readObject();

        System.out.println(d2.c.r.j);
    }

}

Customized Serialization:
package com.cerotid.fundamentals;

import java.io.*;

class Account implements Serializable {
    String userName = "ram";
    transient String passWord = "neupanram";
}

public class CustomizedSerializeDemo {

    public static void main(String[] args) throws Exception {

        Account a1 = new Account();
        System.out.println(a1.userName + "...." + a1.passWord);

        FileOutputStream fos = new FileOutputStream("abc.ser");
        ObjectOutputStream oos = new ObjectOutputStream(fos);
        oos.writeObject(a1);

        FileInputStream fis = new FileInputStream("abc.ser");
        ObjectInputStream ois = new ObjectInputStream(fis);

        /*Object o = ois.readObject();
        if (o instanceof Account) {
            Account a2 = (Account) o;
        }*/
        Account a2 = (Account) ois.readObject();
        System.out.println(a2.userName + "..." + a2.passWord);
    }

}
Output:
ram....neupanram
ram...null

To show password also:
package com.cerotid.fundamentals;

import java.io.*;

class Account implements Serializable {
    String userName = "ram";
    transient String passWord = "neupanram";

    private void writeObject(ObjectOutputStream oos) throws Exception {
        oos.defaultWriteObject(); //meant for default serialization
        String epassword = "123" + passWord; //prepare encripted password
        oos.writeObject(epassword); //write encripted password to the file
    }

    private void readObject(ObjectInputStream ois) throws Exception {
        ois.defaultReadObject(); //meant for default deserialization
        String epwd = (String) ois.readObject(); //read encripted password
        passWord = epwd.substring(3);            //perform decription
    }
}

public class CustomizedSerializeDemo {

    public static void main(String[] args) throws Exception {

        Account a1 = new Account();
        System.out.println(a1.userName + "...." + a1.passWord);

        FileOutputStream fos = new FileOutputStream("abc.ser");
        ObjectOutputStream oos = new ObjectOutputStream(fos);
        oos.writeObject(a1);

        FileInputStream fis = new FileInputStream("abc.ser");
        ObjectInputStream ois = new ObjectInputStream(fis);

        Account a2 = (Account) ois.readObject();
        System.out.println(a2.userName + "..." + a2.passWord);
    }

}
The most important Example:
package com.cerotid.fundamentals;

import java.io.*;

class Account implements Serializable {
    String userName = "ram";
    transient String password = "neupanram";
    transient int pin = 1234;

    private void writeObject(ObjectOutputStream oos) throws Exception {
        oos.defaultWriteObject(); //meant for default serialization
        String epassword = "123" + password; //prepare encripted password
        int epin = 4444+pin;
        oos.writeObject(epassword); //write encripted password to the file
        oos.writeInt(epin);
    }

    private void readObject(ObjectInputStream ois) throws Exception {
        ois.defaultReadObject(); //meant for default deserialization
        String epassword = (String) ois.readObject(); //read encripted password
        int epin = ois.readInt();
        password = epassword.substring(3);            //perform decription
        pin = epin-4444;
    }
}

public class CustomizedSerializeDemo {

    public static void main(String[] args) throws Exception {

        Account a1 = new Account();
        System.out.println(a1.userName + "...." + a1.password+"..."+a1.pin);

        FileOutputStream fos = new FileOutputStream("abc.ser");
        ObjectOutputStream oos = new ObjectOutputStream(fos);
        oos.writeObject(a1);

        FileInputStream fis = new FileInputStream("abc.ser");
        ObjectInputStream ois = new ObjectInputStream(fis);

        Account a2 = (Account) ois.readObject();
        System.out.println(a2.userName + "..." + a2.password+"..."+a2.pin);
    }

}

Serialization with respect to Inheritance:
package com.cerotid.fundamentals;

import java.io.*;

class Animal implements Serializable {
    int i = 10;
}

class Tiger extends Animal {
    int j = 20;
}

public class SerializationInheritanceDemo {

    public static void main(String[] args) throws Exception {
        Tiger t1 = new Tiger();
        System.out.println(t1.i + "..." + t1.j);

        FileOutputStream fos = new FileOutputStream("abc.ser");
        ObjectOutputStream oos = new ObjectOutputStream(fos);
        oos.writeObject(t1);

        FileInputStream fis = new FileInputStream("abc.ser");
        ObjectInputStream ois = new ObjectInputStream(fis);
        Tiger t2 = (Tiger) ois.readObject();
        System.out.println(t2.i + "..." + t2.j);

    }

}

When the parent class does not implement Serializable interface, we can still serialize Child class object if the Child class implements Serilizable interface. 
package com.cerotid.fundamentals;
import java.io.*;
class Animal {
    int i = 10;
    Animal(){
        System.out.println("Animal constructor");
    }
}

class Hen extends Animal implements Serializable{
    int j = 20;
    Hen(){
        System.out.println("Hen constructor");
    }
}
public class SerializeInheritanceDemo2 {
public static void main(String[] args) throws Exception{
    Hen h1 = new Hen();
    h1.i = 888;
    h1.j = 999;
    
    FileOutputStream fos = new FileOutputStream("abc.ser");
    ObjectOutputStream oos = new ObjectOutputStream(fos);
    oos.writeObject(h1);
    System.out.println("Deserailization started");
    
    FileInputStream fis = new FileInputStream("abc.ser");
    ObjectInputStream ois = new ObjectInputStream(fis);
    Hen h2= (Hen) ois.readObject();
    System.out.println(h2.i + "...."+h2.j);
}
}

  • At the time of serialization, JVM will check if any instance variable is inheriting from non serializable parent or not. If any variable is inheriting from non serializable parent class then JVM ignores original value and save default value to the file. 
  • At the time of deserializable JVM will check if any parent class is Nonserilizable or not. If any parent class is non serilizable then JVM will execute instance control flow in that non serilizable parent and share it instance variables to the current
  • To execute instance control flow execution of non serilizable parent, JVM will always invoke no argument constructor. Otherwise we will get Runtime Exception saying InvalidClassException.

No comments:

Post a Comment