7.5 Transient Fields, Custom Hooks & Externalizable
← Back to Chapter 7: Garbage Collection & Serialization
Standard serialization blindly persists every non-static field in an object, which can leak security secrets or fail when non-serializable references are encountered.
What is Transient?
If you don't want a field to be serialized, use: transient.
Marking a field transient instructs the JVM serializer to ignore that field
Example:
class Employee implements Serializable {
private String name;
// This field will NOT be serialized.
private transient String password;
}
So:
name → serialized ✓
password → skipped ✗
Upon deserialization, transient fields receive their JVM default value (null, 0, false).
Why use transient?
For things like:
passwords
temporary data
sensitive information
fields that shouldn't be persisted/transferred
fields that can be recreated
Serialization vs Deserialization
| Serialization | Deserialization |
|---|---|
| Object → bytes | Bytes → object |
| Used for storing/transferring | Used for reading/restoring |
| ObjectOutputStream | ObjectInputStream |