I'm reading about custom serialization in Java, where you provide the following two methods inside the class that you want to serialize:
private void writeObject(ObjectOutputStream oos)
private void readObject(ObjectInputStream ois)
For example:
public class Employee implements Serializable {
private static final long serialVersionUID = 1L;
private transient Address address;
private Person person;
// setters and getters
private void writeObject(ObjectOutputStream oos)
throws IOException {
oos.defaultWriteObject();
oos.writeObject(address.getHouseNumber());
}
private void readObject(ObjectInputStream ois)
throws ClassNotFoundException, IOException {
ois.defaultReadObject();
Integer houseNumber = (Integer) ois.readObject();
Address a = new Address();
a.setHouseNumber(houseNumber);
this.setAddress(a);
}
}
When you want to deserialize the serialized object of the class Employee as follows:
Employee e2 = (Employee) objectInputStream.readObject();
the Java virtual machine will call the readObject(ObjectInputStream ois) method defined in the class Employee instead of the readObject() of the ObjectInputStream class (source). However, the former method doesn't return anything (void), unlike the latter method which returns an Object type (which should be casted).
So, how do we still get the Employee object from the above custom deserialization process?