Serialization and Deserialization in Java
Serialization is changing the state of Object into binary stream or byte stream. Deserialization is the reverse process where byte stream changes into java object.
The byte stream created is platform-independent. So, the object serialized on one platform can be deserialized on a different platform.
To make a Java object serializable we implement the java.io.Serializable interface.
java.io.Serializable interface
⫸ Serializable is a marker interface (has no data member and method). It is used to "mark" Java classes so that the objects of these classes may get a certain capability. The Cloneable and Remote are also marker interfaces.
⫸ It must be implemented by the class whose object you want to persist.
⫸ The String class and all the wrapper classes implement the java.io.Serializable interface by default.
Advantages of Serialization
- To save/persist state of an object.
- To travel an object across a network.
A Serializable class can declare its own UID explicitly by declaring a field name.It must be static, final and of type long.
Example
- /**
- * @author javalearning
- */
- class Test implements java.io.Serializable {
- public int a;
- public String b;
- /**
- * Constructor
- * @param a
- * @param b
- */
- public Test(int a, String b)
- {
- this.a = a;
- this.b = b;
- }
- }
- /**
- * @author javalearning
- */
- class Main {
- public static void main(String[] args) {
- Test test = new Test(1, "Hello world");
- String filename = "xyz.ser";
- /**
- * Serialization
- */
- try {
- /**
- * Saving of object in a file
- */
- FileOutputStream file = new FileOutputStream(filename);
- ObjectOutputStream out = new ObjectOutputStream(file);
- /**
- * Method for serialization of object
- */
- out.writeObject(test);
- out.close();
- file.close();
- System.out.println("Object serialized");
- }
- catch (IOException ex) {
- System.out.println("IOException");
- }
- Test test1 = null;
- /**
- * Deserialization
- */
- try {
- /**
- * Reading the object from a file
- */
- FileInputStream file = new FileInputStream(filename);
- ObjectInputStream in = new ObjectInputStream(file);
- /**
- * Method for deserialization of object
- */
- test1 = (test) in.readObject();
- in.close();
- file.close();
- System.out.println("Object has been deserialized ");
- System.out.println("a: " + test1.a);
- System.out.println("b: " + test1.b);
- }
- catch (IOException ex) {
- System.out.println("IOException");
- }
- catch (ClassNotFoundException ex) {
- System.out.println("ClassNotFoundException");
- }
- }
- }
ObjectInputStream class
An ObjectInputStream deserializes objects and primitive data written using an ObjectOutputStream.