2

I have read these articles on SO:

Externalizable or Serializable?,

What is the difference between Serializable and Externalizable in Java?.

but my question is what extra customization could be derived by implementing Externalizable as compared to serializable.

It is possible to customize Serialization of a class that implements Serializable by giving our own implementation of writeObject and readObject. Then what is the purpose of using Externalizable and customizing the ReadExternal and writeExternal implementations. what is the real benefit of using Externalizable. I have read various links that says Externalizable supports custom serialization (including the one above). but I do not see an example where Externalizable is a clear winner or something that cannot be done using Serializable. would be nice to see an example on this.

Just to give more clarity, the following snippet, is extracted from here:

When a class implements Serializable interface it gives information to the JVM that the instances of these classes can be serialized. Along with that, there is a special note to the JVM

"look for following two methods in the class that implements Serializable. If found invoke that and continue with serialization process else directly follow the standard serialization protocol"

So this gives us a chance to write these two methods:

private void writeObject(ObjectOutputStream out) throws IOException;, private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException;

inside the Class that implements Serializable and you get a hook to the serialization process. You can write your custom code inside these two methods and customize the standard behavior of serialization.

Community
  • 1
  • 1
brain storm
  • 30,124
  • 69
  • 225
  • 393

1 Answers1

0

The main difference between Serializable and Externalizable is that Serializable automatically takes care of base classes for you. Externalizable leaves the entire job up to you.

user207421
  • 305,947
  • 44
  • 307
  • 483