I was going through this article to understand more about Java Serialization process. When it comes to uses of readObject/writeObject
I could see two use cases:
writeObject
to encrypt the byte code before it gets serialized. From the security point of view, that's good thing.readObject
to execute any specific piece of code that need to execute immediately after deserialization, and off course from poin#1, we can even use readObject
to decrypt the byte code that was excrypted while serializing the object.Is there any other practical scenario you've come across while serializing/deserializing objects by writing customr readObject/writeObject method? Or If you could point me to any place where I could see some decent and practical uses of readObject/writeObject?
public class Employee implements Serializable {
private static final long serialVersionUID = 1L;
private int empno;
private String ename;
private String job;
// setter & getter
@Override
public String toString() {
return "Employee [empno=" + empno + ", ename=" + ename + ", job=" + job
+ "]";
}
private void writeObject(ObjectOutputStream out) throws IOException {
// default serialization
// out.defaultWriteObject();
// custom serialization
out.writeInt(empno);
out.writeUTF(ename);
// out.writeUTF(job); //job will not serialize
}
private void readObject(ObjectInputStream in) throws IOException,
ClassNotFoundException {
// default deSerialization
// in.defaultReadObject();
// custom deSerialization
empno = in.readInt();
ename = in.readUTF();
// this.job = in.readUTF();
}
}
The writeObject() and readObject() methods are also used for prevention of an Object Serialization.
When a Super class implements Serializable all of its subclasses are serializable by default. But if you want a sub class not to be serializable, override the methods writeObject() and readObject() in the subclass as below
class Parent implements Serailizable
{
int id;
}
class child extends Parent
{
String name;
private void writeObject(ObjectOutputStream out) throws NotSerializableException
{
throw new NotSerializableException();
}
private void readObject(ObjectInputStream in) throws NotSerializableException
{
throw new NotSerializableException();
}
}
Now the objects of subclass cannot be serialized.
Custom readObject
methods are also useful when you need to initialize transient (non-serialized) fields after the object has been deserialized.
BTW, check out Effective Java, Chapter 11 (I'm not sure what the chapter/item number is in the 2nd ed.). It's an excellent read on serialization.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With