Professional Documents
Culture Documents
Serialization basics
Serialization is the process of transforming an in-memory object to a byte stream. Deserialization is the inverse process of reconstructing an object from a byte stream to the same state in which the object was previously serialized. Serializing out and serializing in are also used.
2
Serialization basics
Serialization basics
Serialization code
FileOutputStream out = new FileOutputStream( save.ser ); ObjectOutputStream oos = new ObjectOutputStream( out ); oos.writeObject( new Date() ); oos.close();
Deserialization code
FileInputStream in = new FileInputStream( save.ser ); ObjectInputStream ois = new ObjectInputStream( in ); Date d = (Date) ois.readObject(); ois.close();
Object graphs
If an object has references to other objects or arrays, the entire object graph is serialized when the object is serialized.
The object graph consists of the object directly serialized and any other objects or arrays to which the object has direct or indirect references.
Nonserializable superclasses
If a serializable class C has a nonserializable superclass S, instances of C still can be serialized if S has an accessible no-argument constructor.
Ss no-argument constructor is invoked automatically during deserialization to construct the S-part of the deserialized object.
Technically, primitive types cannot be serialized or deserialized. However, the ObjectOutputStream implements the DataOutput interface, which declares methods such as writeInt to write primitive types to streams. ObjectInputStream implements DataInput for reading primitive types.
9
During deserialization, transient fields are restored to their default values (e.g., transient numeric fields are restored to zero).
10
Customization
Serialization and deserialization can be customized by providing private callback methods named writeObject and readObject, respectively. The Externalizable interface can be implemented by classes that need to have complete control over serialization and deserialization.
11
Conclusion
The same object should not be repeatedly serialized to the same stream. A class should not be redefined in between the serialization and deserialization of its instances. Classes that need to disable serialization can throw a NotSerializableException in the private callback writeObject.
12