Why serialization in Java? When is serialization used?









what is serialization

Serialization (Serialization) is a mechanism for processing object streams, that is, writing objects into IO streams.

The so-called object stream is to stream the content of the object, and the streamed object can be read and written, and the streamed object can also be transmitted between the network; serialization is to solve the problem when the object stream is read and written. problems raised. The idea of ​​serialization is to "freeze" the object state, and then write to disk or transmit in the network; the idea of ​​deserialization is to "unfreeze" the object state and regain the available Java objects.

Implementation of serialization:

The class that needs to be serialized implements the Serializable interface. This interface has no methods that need to be implemented. implements Serializable is just to mark that the object can be serialized; then use an output
stream (such as: FileOutputStream) to construct an ObjectOutputStream (object stream ) object;
then, use the writeObject(Object obj) method of the ObjectOutputStream object to write out the object whose parameter is obj (that is, save its state), and use the input stream to restore it.



when to use serialization

① Object serialization can realize distributed objects. Main applications such as: RMI (remote method invoke, that is, remote method invocation) use object serialization to run services on remote hosts, just like running objects on the local machine.

② Java object serialization not only retains the data of an object, but also recursively saves the data of each object referenced by the object. Entire object hierarchies can be written to a byte stream, which can be saved in a file or passed over a network connection. Object serialization can be used to perform "deep copy" of objects, that is, to copy the object itself and the referenced object itself. Serializing an object may result in the entire object sequence.



Precautions

所有需要网络传输的对象都需要实现序列化接口,通过建议所有的 javaBean 都实现 Serializable 接口。

对象的类名、实例变量(包括基本类型,数组,对其他对象的引用)都会被序列化;方法、类变量、transient 实例变量都不会被序列化。

如果想让某个变量不被序列化,使用 transient 修饰。

序列化对象的引用类型成员变量,也必须是可序列化的,否则,会报错。

反序列化时必须有序列化对象的 class 文件。

当通过文件、网络来读取序列化后的对象时,必须按照实际写入的顺序读取。

单例类序列化,需要重写 readResolve() 方法;否则会破坏单例原则。

同一对象序列化多次,只有第一次序列化为二进制流,以后都只是保存序列化编号,不会重复序列化。

建议所有可序列化的类加上 serialVersionUID 版本号,方便项目升级。











Note:
Likes, comments, and reprints are welcome. Please give the link to the original text in an obvious place on the article page
. Those who know, thank you for reading my article in the vast crowd.
Where is the signature without personality!
For details, please follow me
and continue to update

Scan to have a surprise!
© 2021 03 - Guyu.com | 【Copyright All Infringement Must Be Prosecuted】

Guess you like

Origin blog.csdn.net/weixin_49770443/article/details/114262080