Java Serialization
  • The mechanism that makes persistence possible is called serialization. Object serialization means converting an object into a data stream and writing it to storage.
  • Serializable is a marker interface. It just tells the Object Serialization tools that your class is serializable.
  • All fields except static and transient fields are serialized.

Selective Serialization

If your serializable class contains either of the following two methods (the signatures must be exact), then the default serialization will not take place.

private void writeObject(java.io.ObjectOutputStream out)
throws IOException;
private void readObject(java.io.ObjectInputStream in)
throws IOException, ClassNotFoundException;

You can control how more complex objects are serialized, by writing your own implementations of the writeObject and readObject methods. Implement writeObject when you need to exercise greater control over what gets serialized when you need to serialize objects that default serialization cannot handle, or when you need to add data to the serialization stream that is not an object data member. Implement readObject to reconstruct the data stream you wrote with writeObject.

The Externalizable Interface

Use the Externalizable interface when you need complete control over your bean's serialization (for example, when writing and reading a specific file format). To use the Externalizable interface you need to implement two methods: readExternal and writeExternal. Classes that implement Externalizable must have a no-argument constructor.

Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License