是否在序列化过程中序列化了静态变量 [英] Are static variables serialized in Serialization process

查看:88
本文介绍了是否在序列化过程中序列化了静态变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我偶然发现了java序列化。我在许多文档和书中都读到静态和瞬态变量无法用Java序列化。
我们声明一个serialVersionUid如下。

I'm stumbled upon understanding java serialization. I have read in many documents and books that static and transient variables cannot be serialized in Java. We declare a serialVersionUid as follows.

private static final long serialVersionUID = 1L;

如果静态变量未被序列化,那么在反序列化过程中我们经常会遇到异常。

If a static variable was not serialized then, we often face an exception during the de-serialization process.

java.io.InvalidClassException

,其中提取了反序列化对象的serialVersionUID,并与加载类的serialVersionUID进行比较。

in which the serialVersionUID from the deserialized object is extracted and compared with the serialVersionUID of the loaded class.

据我所知,我认为如果静态变量无法序列化。这个例外毫无意义。我可能错了,因为我还在学习。

To my knowledge i think that if static variables cannot be serialized. There is no point of that exception. I may be wrong because I'm still learning.

java中的静态和瞬态变量无法序列化是一个神话。请纠正我,我对这个概念一团糟。

Is it a myth that "Static and transient variables in java cannot be serialized". Please correct me, I'm in a mess about this concept.

推荐答案

serialVersionUID是特殊序列化和反序列化过程使用的静态变量,用于验证本地类是否与用于序列化对象的类兼容。它不仅仅是一个静态变量,它绝对不是序列化的。

serialVersionUID is a special static variable used by the serialization and deserialization process, to verify that a local class is compatible with the class used to serialize an object. It's not just a static variable as others, which are definitely not serialized.

当一个类的对象首次序列化时,一个类描述符包含类名和串行版本UID写入流。当反序列化时,JVM会检查从流中读取的串行版本UID是否与本地类相同。如果它们不是,它甚至不会尝试反序列化对象,因为它知道类是不兼容的。

When an object of a class is first serialized, a class descriptor containing among other things the class name and serial version UID is written to the stream. When this is deserialized, the JVM checks if the serial version UID read from the stream is the same as the one of the local class. If they're not, it doesn't even try to deserialize the object, because it knows the classes are incompatible.

这篇关于是否在序列化过程中序列化了静态变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆