Why is this an issue?
Fields marked as transient
in a Serializable
class will be ignored during serialization and consequently not written out
to a file (or stream).
This can be useful in situations such as where the content of a field can be recomputed from other fields. To reduce the output size, this field
can be marked as transient
and recomputed when a given object is deserialized.
Since transient
is very specific to classes that implement Serializable
, it is superfluous in classes that do not.
This rule raises an issue when a field is marked as transient
, even though the containing class does not implement
Serializable
.
How to fix it
Ask yourself whether this class should be serializable. If yes, ensure it implements Serializable
and provides any additional logic
required to serialize and deserialize an instance of this type. Otherwise, remove the transient
modifier from this field.
Code examples
Noncompliant code example
class Vegetable {
private transient Season ripe; // Noncompliant, the "Vegetable" class does not implement "Serializable" but the field is marked as "transient"
// ...
}
Compliant solution
class Vegetable {
private Season ripe; // Compliant, the field is not marked as "transient"
// ...
}
Resources