Skip to content

Serializable

nhan.nguyen edited this page Sep 14, 2023 · 10 revisions

Introduction Serialization, Deserialization

  • Serialization is a mechanism of converting the state of an object into a byte stream.
  • Deserialization is the reverse process where the byte stream is used to recreate the actual Java object

Java-Serialization-Flow

How to use Serialization?

  • A Java object is serializable if its class or any of its superclasses implements either the java.io.Serializable interface or its subinterface, java.io.Externalizable
  • The Serializable interface has no methods or fields and serves only to identify the semantics of being serializable.
  • Serialization in java is implemented by ObjectInputStream and ObjectOutputStream, so all we need is a wrapper over them to either save it to file or send it over the network. Ex:
Screen Shot 2023-09-05 at 09 46 00 Screen Shot 2023-09-05 at 09 46 59 Screen Shot 2023-09-05 at 09 47 10

Some characteristics of serialization

  • If a parent class has implemented Serializable interface then child class doesn’t need to implement it but vice-versa is not true.
  • Only non-static data members are saved via Serialization process.
  • Static data members and transient data members are not saved via Serialization process. So, if you don’t want to save value of a non-static data member then make it transient.
  • Constructor of object is never called when an object is deserialized.
  • Associated objects must be implementing Serializable interface.
Screen Shot 2023-09-14 at 14 23 52

What is the serialVersionUID?

  • The serialVersionUID attribute is an identifier that is used to serialize/deserialize an object of a Serializable class.
  • We use the serialVersionUID attribute to remember versions of a Serializable class to verify that a loaded class and the serialized object are compatible.
  • If we don’t define a serialVersionUID state for a Serializable class, then Java will define one based on some properties of the class itself such as the class name, instance fields, and so on.

It's only suitable for the old infrastructure. Current when services can communicate via REST, HTTP.