How does Externalizable differ from Serializable? [duplicate]
Asked Answered
C

2

6

I read that

Externalizable provides us writeExternal() and readExternal() method which gives us flexibility to control java serialization mechanism instead of relying on Java's default serialization.

But If i implement Serializable and override readObject(), writeObject(), then does not it also means the same that I am customizing serialization process?

How does it differ?

THanks.

Clapboard answered 27/8, 2013 at 18:44 Comment(0)
E
6

Difference between Externalizable and Serializable

  1. In case of Serializable, default serialization process is used. while in case of Externalizable custom Serialization process is used which is implemented by application.
  2. JVM gives call back to readExternel() and writeExternal() of java.io.Externalizalbe interface for restoring and writing objects into persistence.
  3. Externalizable interface provides complete control of serialization process to application.
  4. readExternal() and writeExternal() supersede any specific implementation of writeObject and readObject methods.

Though Externalizable provides complete control, it also presents challenges to serialize super type state and take care of default values in case of transient variable and static variables in Java. If used correctly Externalizable interface can improve performance of serialization process.

So go for Externalizable interface

When you have special requirements for the serialization of an object. For example, you may have some security-sensitive parts of the object, like passwords, which you do not want to keep and transfer somewhere. Or, it may be worthless to save a particular object referenced from the main object because its value will become worthless after restoring.

Ergosterol answered 27/8, 2013 at 18:51 Comment(1)
@Prabhaker...don't you think same can be achieved using Custom Serialization (writeObject and readObject)?Steib
N
3

Official docs on Bean Persistence

Implement writeObject when you need to exercise greater control over what gets serialized when you need to serialize objects that default serialization cannot handle, or when you need to add data to the serialization stream that is not an object data member. Implement readObject to reconstruct the data stream you wrote with writeObject.

Use the Externalizable interface when you need complete control over your bean's serialization (for example, when writing and reading a specific file format). To use the Externalizable interface you need to implement two methods: readExternal and writeExternal. Classes that implement Externalizable must have a no-argument constructor.

Nidanidaros answered 27/8, 2013 at 18:51 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.