1

I am learning java serialization and i have a doubt, if one can customize the default serialization process by overriding the writeObject() and readObject() methods in class then what is the use of the Externalizable interface? in which scenario it is needed?

Shivayan Mukherjee
  • 766
  • 3
  • 10
  • 33
  • Overriding from where? Those are not defined in Object class. If you want to customize serialization of an object then it should implement ```Externalizable``` to customize serialization with overriding ```writeExternal(ObjectOutput out)``` and ```readExternal(ObjectInput in)``` to make it ```Serializable```. Unless any object serializable it cant be sent over the network or written to file with any of the streams. If you try so it will throw ```NotSerializableException``` – Nitin Zadage Jul 10 '19 at 07:20
  • @Nitin That is not correct. It is also possible to *provide* custom `readObject()/writeObject()` methods without using `Externalizable` at all, and *that is what the question is about.* – user207421 Jul 10 '19 at 07:55
  • @OP `Externalizable` makes you responsible for serializing the super class's state, for one thing, and has no default behaviour, for another. – user207421 Jul 10 '19 at 07:56
  • user7294900's answer stands valid in that case. – Nitin Zadage Jul 10 '19 at 07:59
  • Valid but pretty useless. Answers in the duplicate are much better. – user207421 Jul 10 '19 at 08:12

1 Answers1

1

It's used for custom serialization, see Guide to the Externalizable

Main usage:

change the JVM’s default serialization behavior.

Use case:

If we need to serialize the entire object, the Serializable interface is a better fit. On the other hand, for custom serialization, we can control the process using Externalizable.

Possible performance advantage:

The java.io.Serializable interface uses reflection and metadata which causes relatively slow performance. By comparison, the Externalizable interface gives you full control over the serialization process.

Community
  • 1
  • 1
Ori Marko
  • 56,308
  • 23
  • 131
  • 233