首页 > 代码库 > "Serializable" classes should have a version id
"Serializable" classes should have a version id
A serialVersionUID
field is required in all Serializable
classes. If you do not provide one, one will be calculated for you by the compiler. The danger in not explicitly choosing the value is that when the class changes, the compiler will generate an entirely new id, and you will be suddenly unable to deserialize (read from file) objects that were serialized with the previous version of the class.
serialVersionUID
‘s should be declared with all of these modifiers: static final long
.
Noncompliant Code Example
public class Raspberry extends Fruit // Noncompliant; no serialVersionUID. implements Serializable { private String variety; public Raspberry(Season ripe, String variety) { ...} public void setVariety(String variety) {...} public String getVarity() {...} } public class Raspberry extends Fruit implements Serializable { private final int serialVersionUID = 1; // Noncompliant; not static & int rather than long
Compliant Solution
public class Raspberry extends Fruit implements Serializable { private static final long serialVersionUID = 1; private String variety; public Raspberry(Season ripe, String variety) { ...} public void setVariety(String variety) {...} public String getVarity() {...} }
Exceptions
Swing and AWT classes, abstract
classes, Throwable
and its subclasses (Exception
s and Error
s), and classes marked with @SuppressWarnings("serial")
are ignored.
"Serializable" classes should have a version id
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。