If a serializable class is serialized using the default Java serialization mechanism, each non-static, non-transient field in the class must also be serializable. Otherwise, the class generates a java.io.NotSerializableException as its fields are written out by ObjectOutputStream.writeObject.

As an exception, classes that define their own readObject and writeObject methods can have fields that are not themselves serializable. The readObject and writeObject methods are responsible for encoding any state in those fields that needs to be serialized.

To avoid causing a NotSerializableException, do one of the following:

In the following example, WrongPerformanceRecord contains a field factors that is not serializable but is in a serializable class. This causes a java.io.NotSerializableException when the field is written out by writeObject. However, PerformanceRecord contains a field factors that is marked as transient, so that the serialization mechanism skips the field. This means that a correctly serialized record is output by writeObject.

In this second example, WrongPair takes two generic parameters L and R. The class itself is serializable, but users of this class are not forced to pass serializable objects to its constructor, which could lead to problems during serialization. The solution is to set upper type bounds for the parameters, to force the user to supply only serializable objects. A similar example is the WrongEvent class, which takes a weakly typed eventData object. A better solution is to force the user to supply an object whose class implements the Serializable interface.

  • Java API Specification: Serializable, ObjectOutputStream.