Transient Fields in Serializable
ID |
java.transient_fields_in_serializable |
Severity |
info |
Remediation Complexity |
trivial |
Remediation Risk |
low |
Remediation Effort |
low |
Resource |
Reliability |
Language |
Java |
Tags |
CWE:594, best-practice, reliability |
Description
Reports non-transient, non-static fields in classes implementing Serializable whose declared type is known to be non-serializable (e.g., Thread, Connection, Socket).
Rationale
When a Serializable object is written to an ObjectOutputStream, all non-transient instance fields are serialized. If a field holds a non-serializable object, a NotSerializableException is thrown at runtime:
class ServerHandler implements Serializable {
private Thread workerThread; // Throws at serialization
private Connection dbConnection; // Throws at serialization
}
Remediation
Mark non-serializable fields as transient so they are excluded from serialization. Provide custom readObject() / writeObject() methods if the field’s state must be preserved:
class ServerHandler implements Serializable {
private transient Thread workerThread;
private transient Connection dbConnection;
}