If the Serializable
interface is just a Marker-Interface that is used for passing some-sort of meta-data about classes in java - I'm a bit confused:
After reading the process of java's serialization algorithm (metadata bottom-to-top, then actual instance data top-to-bottom), I can't really understand what data cannot be processed through that algorithm.
In short and formal:
- What data may cause the
NotSerializableException
? - How should I know that I am not supposed to add the
implements Serializable
clause for my class?
Anything your
Serializable
class has in it that is notSerializable
will throw this exception. You can avoid it by using thetransient
keyword.Common examples of things you can't serialize include Swing components and Threads. If you think about it it makes sense because you could never deserialize them and have it make sense.
More practically, no object can be serialized (via Java's built-in mechanism) unless its class implements the Serializable interface. Being an instance of such a class is not a sufficient condition, however: for an object to be successfully serialized, it must also be true that all non-transient references it holds must be null or refer to serializable objects. (Do note that that is a recursive condition.) Primitive values, nulls, and transient variables aren't a problem. Static variables do not belong to individual objects, so they don't present a problem either.
Some common classes are reliably serialization-safe. Strings are probably most notable here, but all the wrapper classes for primitive types are also safe. Arrays of primitives are reliably serializable. Arrays of reference types can be serialized if all their elements can be serialized.
All the primitive data types and the classes extend either Serializable directly,
or indirectly,
SomeClass implements Serializable.
can be serialized. All the fields in a serializable class gets serialized except the fields which are marked
transient
. If a serializable class contains a field which is not serializable(not primitive and do not extend from serializable interface) thenNotSerializableException
will be thrown.Answer to the second question : As @JB Nizet said. If you are going to write the instance of a class to some stream then and then only mark it as Serializable, otherwise never mark a class Serializable.