The main benefit of externalization over serialization is that externalization persists only part of the object, not the whole object as in case of serialization. But i think that we can simulate externalization via custom serialization if we will not call defaultWriteObject() method of ObjectOutputStream in writeObject() method of the serializable class. So without calliing defaultWriteObject() method and only persisting the needed instance variables of serializable class in writeObject() method we can achieve externalization benefits.
Here is an example demonstrating the aforementioned things:
package com.test;
import java.io.*;
public class Test {
public static void main(String[] args) throws FileNotFoundException, IOException, ClassNotFoundException {
Dog dog = new Dog();
System.out.println("before serialization: i = " + dog.i + ", j = " + dog.j);
FileOutputStream fos = new FileOutputStream("abc.ser");
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(dog);
FileInputStream fis = new FileInputStream("abc.ser");
ObjectInputStream ois = new ObjectInputStream(fis);
Dog dog2 = (Dog) ois.readObject();
System.out.println("after deserialization: i = " + dog2.i + ", j = " + dog2.j);
}
public static class Dog implements Serializable {
int i = 10;
int j = 20;
private void writeObject(ObjectOutputStream oos) throws IOException{
//oos.defaultWriteObject();
System.out.println("In WriteObject");
oos.writeInt(i);
}
private void readObject(ObjectInputStream ois) throws IOException, ClassNotFoundException {
//ois.defaultReadObject();
System.out.println("In ReadObject");
i = ois.readInt();
}
}
}
The output for this code is:
before serialization: i = 10, j = 20
In WriteObject
In ReadObject
after deserialization: i = 10, j = 0
As you can see, the oos.defaultWriteObject()
and ois.defaultReadObject();
are commented and we persist and restore only the instance variable i
.
So, is my assumption correct that we can simulate externalization concept via custom serialization ?