transient Fields and serialVersionUID
Exclude sensitive fields with transient and maintain version compatibility with serialVersionUID.
Why transient?
Some fields should not be saved: passwords, open file handles, cached computations. Mark them transient and they are skipped during serialization.
public class Session implements Serializable {
private String username;
private transient String password; // NOT serialized
private transient Connection dbConn; // NOT serialized
}Transient Field Value After Deserialization
After deserialization, transient fields receive their Java default value: null for objects, 0 for numbers, false for booleans.
Session s = (Session) ois.readObject();
System.out.println(s.username); // "alice"
System.out.println(s.password); // null (transient)All lessons in this course
- Java Serialization Basics
- transient Fields and serialVersionUID
- Custom Serialization: writeObject and readObject
- Modern Alternatives: JSON and Protocol Buffers