What is Serialization in Java?
The mechanism where an object state is represented as a byte stream. Here, all object data as well as the information regarding the object such as its type are also included.
Deserialization, which is the reverse mechanism can be used to recreate the same object.
Why is Java Serialization important?
How to serialize an object?
- Implement java.io.Serializable interface
- All fields must be serializable. (If a Java Standard class implements java.io.Serializable interface, then it is serializable).
- Whichever fields you do not wish to serialize should be marked as transient.
import java.io.Serializable;
class User implements Serializable {
public int uid;
public String name;
public String address;
}
Now, the class is eligible for Serialization.
The java.io.Serializable interface doesn't declare any methods. It is a marker interface which says that this class can be serialized.
The java.io.Serializable interface doesn't declare any methods. It is a marker interface which says that this class can be serialized.
Serialization
public static void main(String args[]){
try(ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("temp.out"))){
User user = new User();
oos.writeObject(user);
oos.flush();
} catch (FileNotFoundException ex) {
Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
}
}
ObjectOutputStream class is used to serialize an object. Its writeObject method contains the algorithm that requires an object to be serialized.
Deserialization
public static void main(String args[]){
try(ObjectInputStream oin = new ObjectInputStream(new FileInputStream("temp.out"))){
User user = (User) oin.readObject();
System.out.println("User's name: " + user.name);
} catch (FileNotFoundException ex) {
Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
}
}
ObjectInputStream class is used to serialize an object. Its readObject method contains the algorithm that requires an object to be deserialized.
Serialization algorithm in brief
- Write the metadata of the class associated with an instance.
- Recursively write the description of the superclass until it finds
java.lang.object
. - Once it finishes, start with the actual data associated with the instance starting from the topmost superclass.
- Recursively write the data associated with the instance, starting from the least superclass to the most-derived class.
Comments
Post a Comment