dharag
dharag

Reputation: 299

Why Custom Java Serialization

I understand we can to custom serialization by overriding readObject() and writeObject(). But what could be the need to do this ? Use cases ?

Also, Externalizable interface is also just a way to provide custom serialization or does it serve any other purpose ?

Upvotes: 0

Views: 106

Answers (2)

Marko Topolnik
Marko Topolnik

Reputation: 200138

A familiar example from practice: HashMap. It has a lot of complex internal structure, yet has a fairly simple API, even including the customization parameters. If it used default serialization, it would have to serialize a fair amount of redundant information: empty buckets, empty parts of buckets, all the indices into the arrays, etc.

Instead, HashMap defines a simple and straightforward serialized form which transfers all, and no more than, the data needed to reconstruct it at the other end.

Upvotes: 3

JB Nizet
JB Nizet

Reputation: 691625

Use cases, out of the top of my head:

  • restoring values of transient variables that are computed from other non-transient ones
  • using a more compact, more efficient representation of the object for serialization than the default one
  • maintain backward compatibility with previous versions of the class

the javadoc of Externalizable explains what it's used for.

Upvotes: 3

Related Questions