Menu
Topics Index
...
`


Input/Output: Exploring java.io > Serialization >
Siva Nookala - 01 Apr 2016
Serialization can be done using two interfaces - one is Serialization In Java interface and the other is Externalizable interface. While Serializable is convenience interface which saves and restores every member variable of the class, Externalizable helps in controlling what gets saved and restored.

class Student implements Serializable
{
    String name;
    int rollNumber;
    char section;
}


For e.g., in the Student class if we do not want to store the section variable, then we can implement Externalizable interface to achieve this. The Student class can be rewritten as
class Student implements Externalizable
{
    String name = "";
    int rollNumber = 0;
    char section = 'A';
    // WITH OUT THIS CONSTRUCTOR, DE-SERIALIZATION FAILS
    public Student() // LINE A
    {
    }

    public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException
    {
        name = in.readUTF();
        rollNumber = in.readInt();
    }

    public void writeExternal(ObjectOutput out) throws IOException
    {
        out.writeUTF(name);
        out.writeInt(rollNumber);
    }
}
As shown above we need to implement the two methods of Externalizable. They are readExternal and writeExternal. writeExternal is used while serializing the object/writing to the external source like file, network or some other input stream. Where as readExternal is used for de-serializing/reading the data from external sources. Note that we need to define a constructor for the de-serialization to work. If there is no constructor as shown at LINE A, then while de-serializing, it throws InvalidClassException.

An example showing how the Student object can be serialized is explained at Java Serialization Process -.

  • Use Serializable instead Externalizable : Unless specifically required to control what variables get written or how they are written, it is better to use Serialization In Java interface. The advantages for Serializable are that we do not need to implement these two methods readExternal and writeExternal. Not only that, it will become difficult to maintain since every time a new member variable like address or percentage gets added to Student, you need to remember and change these methods. Where as for Serializable it is automatically taken care.

0
Wrong
Score more than 2 points

© meritcampus 2019

All Rights Reserved.

Open In App