Working with Serialization

1. Implementing Serializable Interface

Example: Serializable

public class User implements Serializable {
    private static final long serialVersionUID = 1L;
    private String name;
    private transient String password;   // not serialized
}
AspectDetail
Marker interfaceNo methods
Required fieldserialVersionUID recommended
Excluded fieldstransient and static

2. Using ObjectOutputStream

MethodUse
writeObject(o)Serialize object graph
writeInt/Double/UTFPrimitive writes
flush() / close()Resource management

3. Using ObjectInputStream

Example: Read object

try (ObjectInputStream in = new ObjectInputStream(Files.newInputStream(path))) {
    User u = (User) in.readObject();
}
MethodUse
readObject()Returns Object — cast required
ThrowsClassNotFoundException, InvalidClassException

4. Understanding serialVersionUID

AspectDetail
PurposeVersion identifier for class
MismatchThrows InvalidClassException
Auto-computedBased on class structure (fragile)
RecommendationAlways declare explicitly

5. Using transient Keyword

EffectDetail
Skip serializationField not written
On deserializationField gets default value (0/null/false)
Use forPasswords, caches, computed fields

6. Customizing Serialization

Example: Custom serialization

private void writeObject(ObjectOutputStream out) throws IOException {
    out.defaultWriteObject();
    out.writeInt(computedValue);
}
private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
    in.defaultReadObject();
    this.computedValue = in.readInt();
}
private Object readResolve() { return Singleton.INSTANCE; }
HookUse
writeObject/readObjectCustom format
readResolveReplace deserialized object (singletons)
writeReplaceSubstitute before write

7. Implementing Externalizable Interface

AspectDetail
MethodswriteExternal/readExternal
ConstructorMust have public no-arg
Use caseFull control over format (rare)

8. Understanding Serialization Security Concerns

RiskDetail
Deserialization attacksHostile streams can execute arbitrary code via gadget chains
MitigationUse ObjectInputFilter to whitelist classes
Modern alternativeJSON/Protobuf/Avro/CBOR
Warning: Java serialization is widely considered legacy. Prefer JSON/Protobuf for new code.

9. Handling Versioning Issues

Compatible ChangeIncompatible Change
Add field (default value used)Change field type
Add methodRemove field (with old data)
Make non-finalMove class to different package

10. Using Serialization Proxy Pattern

StepDetail
1. Inner proxy classHolds simplified state
2. writeReplace()Returns proxy instead of self
3. readResolve()Reconstruct from proxy
4. Block direct deserializationreadObject throws