0

Recently from any source, I came to know that custom serialisation is a process where we can define writeObject(ObjectOutputStream os) and readObject(ObjectInputStream is) in our Serializable class, and these methods will be executed at the time of serialisation and de-serialisation respectively to perform our functionality.

Later on, I came to know that Externalisation is an interface which defines 2 methods: 1- writeExternal() 2- readExternal()

Our class can implement Externalizable and override these methods when we don't want to serialise whole object. These methods will be executed at the time of serialisation and de-serialisation.

I have a doubt that why can't we use custom serialisation by implementing Serializable and defining writeObject(ObjectOutputStream os) and readObject(ObjectInputStream is) methods even to serialise some attributes of an object. Why this externalisation came into the picture.

Thanks,

1 Answers1

0

Externalizable was introduced way before Serializable interface during JDK 1.1 days. During that time, the programmer had to write the exact logic how the object shall be serialized, ie, everything that shall occur inside the writeExternal() and readExternal() had to be written explicitly. Serializable was introduced later to get rid of this headache.

But in some cases, using Externalizable has its own advantages as it allows you to define how the class shall be serialized in your own way rather than depending on what is defined underneath the hood by Java language APIs. I think your class may fall under this category.

To answer your question added in the last part, you can achieve selective serialization of members inside a class by marking them as transient.

Kavitha Karunakaran
  • 1,340
  • 1
  • 17
  • 32