Definition
Serialization is a process in which current state of Object will be saved in stream of bytes. As byte stream create is platform neutral hence once objects created in one system can be deserialized in other platform.
This Byte stream can be used for different purpose.
- Write to Disk
- Store in Memory
- Sent byte stream to other platform over network
- Save byte stream in DB(As BLOB)
Java has already provided out of the box way(java.io.Serializable Interface) to serialize an Object. If you want any class to be serialized then that class needs to implement this interface.
* Serializable interface is just a marker interface. There is no methods in it.
Example. Serializable Class
The serialVersionUID is used as a version control in a Serializable class. If you do not explicitly declare a serialVersionUID, JVM will do it for you automatically, based on various aspects of your Serializable class.
package com.chang; import java.io.Serializable; public class Employee implements Serializable{ public String firstName; public String lastName; // serialVersionUID private static final long serialVersionUID=1L; }
Serializable class usually makes files variables as private and interact with them using setter and getter.
Example. Serialization Class
package com.chang; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectOutputStream; public class SerializationClass{ public static void main(String[] args){ Employee emp = new Employee(); emp.firstName = "Chang"; emp.lastName = "Park"; try{ FileOutputStream fileOut = new FileOutputStream("./employee.txt"); ObjectOutputStream out = new ObjectOutputStream(fileOut); out.wirteObject(emp); out.close(); fileOut.close(); System.out.println("Serialized data is saved in ./employee.txt file"); } catch (IOException i){ i.printStackTrace(); } } }
Example. Deserialization Class
package com.chang; import java.io.*; public class DeserializationClass{ public static void main(String[] args){ Employee emp = null; try{ FileInputStream fileIn = new FileInputStream("./employee.txt"); ObjectInputStream in = new ObjectInputStream(fileIn); emp = (Employee) in.readObject(); in.close(); fileIn.close(); } catch (IOException i){ i.printStackTrace(); return; } catch (ClassNotFoundException c){ System.out.println("Employee class not found"); c.printStackTrace(); return; } System.out.println("First Name of Employee: " + emp.firstName); System.out.println("Last Name of Employee: " + emp.lastName); } }