rspec/rules/S2057/java/rule.adoc
Fred Tingaud 16f6c0aecf
Inline adoc when include has no additional value (#1940)
Inline adoc files when they are included exactly once.

Also fix language tags because this inlining gives us better information
on what language the code is written in.
2023-05-25 14:18:12 +02:00

67 lines
2.1 KiB
Plaintext

== Why is this an issue?
A ``++serialVersionUID++`` field is strongly recommended 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
[source,java]
----
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
[source,java]
----
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
Records, Swing and AWT classes, ``++abstract++`` classes, ``++Throwable++`` and its subclasses (``++Exception++``s and ``++Error++``s), and classes marked with ``++@SuppressWarnings("serial")++`` are ignored.
== Resources
* https://wiki.sei.cmu.edu/confluence/x/ajdGBQ[CERT, SER00-J.] - Enable serialization compatibility during class evolution
* https://docs.oracle.com/en/java/javase/16/docs/specs/serialization/serial-arch.html#serialization-of-records[Record Serialization] - Serialization of Records
ifdef::env-github,rspecator-view[]
'''
== Implementation Specification
(visible only on this page)
=== Message
* Add a "static final long serialVersionUID" field to this class.
* Make this "serialVersionUID" field "(static|final|long)".
endif::env-github,rspecator-view[]