Java: What can and what can't be serialized?

2019-02-04 10:29发布

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:

  1. What data may cause the NotSerializableException?
  2. How should I know that I am not supposed to add the implements Serializable clause for my class?

9条回答
Lonely孤独者°
2楼-- · 2019-02-04 10:56

Anything your Serializable class has in it that is not Serializable will throw this exception. You can avoid it by using the transient 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.

查看更多
Rolldiameter
3楼-- · 2019-02-04 10:59

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.

查看更多
爷、活的狠高调
4楼-- · 2019-02-04 11:03

All the primitive data types and the classes extend either Serializable directly,

class MyClass extends Serializable{
}

or indirectly,

class MyClass extends SomeClass{
}

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) then NotSerializableException 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.

查看更多
登录 后发表回答