why we have Externalizable when we can override writeObject and readObject in java
Asked Answered
A

3

19

As we can override the default serialization process by overriding writeObject() and readObject() , then What is the need of Externalizable interface?

Ascent answered 17/5, 2013 at 9:9 Comment(1)
Can you add an example of a Serializable class with these methods?Consistence
N
5

Class implementing Serializable may or may not wish to change the format in which the instance of that class, written into the stream.

But, Class implementing Externalizable must implement writeExternal and readExternal methods, and its the class's responsibility to write and restore the data to/from the stream.

Navvy answered 17/5, 2013 at 9:34 Comment(0)
H
4

this question has some reasonable answer here

"The CPU cost of serializing Java objects can be significant. This expense, in turn, affects JMS Object messages. You can offset this cost, to some extent, by having application objects implement java.io.Externalizable, but there still will be significant overhead in marshalling the class descriptor. To avoid the cost of having to write the class descriptors of additional objects embedded in an Object message, have these objects implement Externalizable, and call readExternal and writeExternal on them directly. For example, call obj.writeExternal(stream) rather than stream.writeObject(obj). Using Bytes and Stream messages is generally a preferred practice."

this is The best rationale I've been able to find (in Oracle documentation) is in the WebLogic JMS Best Practice document:

Hogarth answered 24/7, 2018 at 10:12 Comment(0)
W
-1

Serializable interface is implement for getting an automatic serialization functionality but if you like to provide your own serialization logic(custom logic) you would go for Externalizable interfaces. Externalizable interface contains two methods which you have to implement that is readExternal() and writeExternal().

If you implement Serializable interface everything including the state of all the Base Classes (Super Classes) are taken care by the default(automatic) Serialization process .

Wharton answered 17/5, 2013 at 9:34 Comment(1)
You can have custom logic by overriding readObject and writeObject methods.Frontage

© 2022 - 2024 — McMap. All rights reserved.