Serialization in Java
Serialization is the process of converting a data structure into a linear sequence of bytes for further transmission or storage. The serialized objects can then be restored (deserialized).
In Java, according to the Java Object Serialization specification, there are two standard serialization methods: standard serialization, using the java.io.Serializable interface, and "extended" serialization - java.io.Externalizable.
Serialization allows you to change the class within certain limits. Here are the most important changes that the Java Object Serialization specification can handle automatically:
- adding new fields to the class
- changing fields from static to non-static
- changing fields from transit to non-transit
Reverse changes (from non-static to static fields and from non-transit to transit) or deletion of fields require some additional processing depending on how much backward compatibility is required.
Serialization/deserialization process using Serializable
When using Serializable, a serialization algorithm is used that, using the Reflection API, does:
- writing to the metadata stream about the class associated with the object (class name, SerialVersionUID identifier, class field identifiers);
- recursive writing to the superclass description stream up to the java.lang.Object class (not inclusive);
- writing the primitive values of the fields of the serializable instance, starting with the fields of the topmost superclass;
- recursively writing objects that are fields of the object being serialized.
In this case, previously serialized objects are not re-serialized, which allows the algorithm to work correctly with circular references.
To perform deserialization, memory is allocated for the object, after which its fields are filled with values from the stream. The object's constructor is not called. However, during deserialization, the constructor without parameters of the parent non-serializable class will be called, and its absence will result in a deserialization error.
Read also:
Comments
Post a Comment