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.
时间: 2024-11-05 12:32:17