Appearance
Lesson 03 · Serialization
Objectives
After this lesson you will be able to:
- Make a class
Serializableand write/read it with object streams. - Use
transientandserialVersionUIDcorrectly. - Recognize serialization pitfalls.
Serializable and object streams
Implementing the marker interface Serializable (no methods) lets ObjectOutputStream / ObjectInputStream convert an object graph to/from bytes.
java
class Account implements Serializable {
private static final long serialVersionUID = 1L;
String owner;
transient String sessionToken; // NOT serialized
}
try (var out = new ObjectOutputStream(Files.newOutputStream(p))) {
out.writeObject(account);
}
try (var in = new ObjectInputStream(Files.newInputStream(p))) {
Account a = (Account) in.readObject(); // throws ClassNotFoundException if class missing
}transient
A transient field is skipped during serialization; on read-back it gets the type's default (null, 0, false) — the constructor does not run. Use it for secrets, caches, and non-serializable references.
java
account.sessionToken = "secret";
// after round-trip:
a.sessionToken == null; // true — transient was not stored, no constructor ranExam trap
Deserialization bypasses constructors — the object is rebuilt from bytes, not constructed. Every non-transient, non-static field must itself be Serializable, or writeObject throws NotSerializableException. static fields belong to the class, not the instance, so they are never serialized.
serialVersionUID
This static final long is the class's version stamp. On read, the JVM compares the stored UID to the current class's; a mismatch throws InvalidClassException. If you don't declare one, the compiler generates a fragile value from the class shape that changes on almost any edit.
java
private static final long serialVersionUID = 1L; // declare it explicitlySDET note
Java's built-in serialization is brittle and a known security risk (deserializing untrusted bytes can execute code). For real persistence/transport prefer an explicit format — JSON (Module 17) — and treat Serializable mostly as exam knowledge. Never readObject untrusted data.
Key Takeaways
Serializableis a marker interface enablingObjectOutputStream/ObjectInputStream(writeObject/readObject).transientfields are skipped (restored to defaults); deserialization bypasses constructors.- Every non-transient, non-static field must be
Serializableor you getNotSerializableException; statics aren't serialized. - Declare
serialVersionUIDexplicitly; a mismatch on read throwsInvalidClassException.
Lesson Quiz
What happens to a transient field after a serialize/deserialize round-trip?
A non-transient field's type is not Serializable. What happens on writeObject?
What does deserialization use to build the object?
A serialVersionUID mismatch on read throws...
Are static fields serialized?
Next: Module 08 Mini-Exam. Run the matching code in labs/src/main/java/com/jse21/m08_io/.