Custom Serialization Example in Java
When we implement the Serializable interface from our class then our class to be serializable.This is enough to support the default Java serialization mechanism. When we need to implement custom serialization we also have to define writeObject() and readObject() methods in our class. Why did I mentioned define these methods and not override? Because we are actually not overriding anything.The JVM checks and calls these methods by using reflection API.
Let's define a simple class to use in this example
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
public class CustomSerialization implements Serializable {
private static final long serialVersionUID = -251814654561166759230L;
private String name;
private String address;
public TestClass(String name, String address) {
this.name= name;
this.address= address;
}
private void writeObject(ObjectOutputStream o)
throws IOException {
o.writeObject(name);
o.writeObject(address);
}
private void readObject(ObjectInputStream o)
throws IOException, ClassNotFoundException {
name= (String) o.readObject();
address= (String) o.readObject();
}
}
public String getName() {
return name;
}
public String getAddress() {
return address;
}
}
We have defined two properties: name and address. We have also defined writeObject() and readObject() methods, and once again note that we are not overriding anything as these methods will be called by the JVM using reflection (we actually defined these methods as private).
Let's define a simple class to test our example:
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
public class CustomSerializeTest{
public static void main(String[] args) throws Exception {
CustomSerialization custom= new CustomSerialization ("Rohit", "Hyderabad");
// serialize the object
FileOutputStream fos = new FileOutputStream("testfile");
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(custom);
oos.flush();
oos.close();
// deserialize the object
FileInputStream fis = new FileInputStream("testfile");
ObjectInputStream ois = new ObjectInputStream(fis);
customRead= (CustomSerialization ) ois.readObject();
ois.close();
System.out.println("--Read object--");
System.out.println("name: " + customRead.getName());
System.out.println("address: " + customRead.getAddress());
}
}