乐闻世界logo
搜索文章和话题

**How Objects Are Serialized in Java?**

2月7日 00:13

In Java, object serialization refers to the process of converting an object's state into a byte sequence, enabling the object to be stored or transmitted over a network. Object serialization is primarily achieved by implementing the java.io.Serializable interface. It is a marker interface that contains no methods and is solely used to indicate that an object of the class can be serialized.

The specific serialization process typically involves the following steps:

  1. Implementing the Serializable Interface: To make a Java class serializable, the class must implement the java.io.Serializable interface.

  2. ObjectOutputStream: Use the ObjectOutputStream class to write objects into a stream. This class has a writeObject() method used to serialize the specified object and output it to the output stream.

  3. Serialization Process: When an object is written using the writeObject() method, the Java Virtual Machine (JVM) first checks if the object has already been serialized. If not, the JVM records the object's type and state (i.e., the values of its member variables) and recursively processes all referenced objects.

  4. transient Keyword: If you do not want a field to be serialized, you can use the transient keyword to modify the field. Fields marked with transient are ignored during object serialization.

  5. UID: Declaring a static constant named serialVersionUID in the class can explicitly define the serialization version UID. This helps ensure serialization compatibility, allowing old serialized objects to be deserialized even when the class definition changes.

Deserialization is the reverse process, primarily implemented using the ObjectInputStream class and its readObject() method to restore the byte sequence into a Java object.

标签:Java