问题描述
当缺少 serialVersionUID
时,Eclipse会发出警告。
Eclipse issues warnings when a serialVersionUID
is missing.
什么是 serialVersionUID
,为什么它很重要?请举例说明缺少 serialVersionUID
会导致问题。
What is serialVersionUID
and why is it important? Please show an example where missing serialVersionUID
will cause a problem.
推荐答案
可能与你得到的解释一样好:
The docs for java.io.Serializable
are probably about as good an explanation as you'll get:
ANY-ACCESS-MODIFIER static final long serialVersionUID = 42L;
如果可序列化类没有明确声明 serialVersionUID
,然后序列化运行时将根据类的各个方面计算该类的默认 serialVersionUID
值,如Java(TM)对象序列化规范中所述。但是,强烈建议所有可序列化类都显式声明 serialVersionUID
值,因为默认 serialVersionUID
计算对类细节非常敏感,这些细节可能因编译器实现而异,因此在反序列化期间可能会导致意外的 InvalidClassExceptions
。因此,为了保证不同java编译器实现中的一致 serialVersionUID
值,可序列化类必须声明显式 serialVersionUID
值。强烈建议显式 serialVersionUID
声明尽可能使用private修饰符,因为此类声明仅适用于立即声明的类 serialVersionUID
字段作为继承成员无效。
If a serializable class does not explicitly declare a serialVersionUID
, then the serialization runtime will calculate a default serialVersionUID
value for that class based on various aspects of the class, as described in the Java(TM) Object Serialization Specification. However, it is strongly recommended that all serializable classes explicitly declare serialVersionUID
values, since the default serialVersionUID
computation is highly sensitive to class details that may vary depending on compiler implementations, and can thus result in unexpected InvalidClassExceptions
during deserialization. Therefore, to guarantee a consistent serialVersionUID
value across different java compiler implementations, a serializable class must declare an explicit serialVersionUID
value. It is also strongly advised that explicit serialVersionUID
declarations use the private modifier where possible, since such declarations apply only to the immediately declaring class serialVersionUID
fields are not useful as inherited members.
这篇关于什么是serialVersionUID,我为什么要使用它?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!