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:
-
Implementing the Serializable Interface: To make a Java class serializable, the class must implement the
java.io.Serializableinterface. -
ObjectOutputStream: Use the
ObjectOutputStreamclass to write objects into a stream. This class has awriteObject()method used to serialize the specified object and output it to the output stream. -
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. -
transient Keyword: If you do not want a field to be serialized, you can use the
transientkeyword to modify the field. Fields marked withtransientare ignored during object serialization. -
UID: Declaring a static constant named
serialVersionUIDin 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.