Contents

Java Serialization

conversion of state of an object into a byte stream
primarily to save to dB or transfer over a network

class needs to implement Serializalble

Serializalble is a marker interface. No memebers. Just adds capabilities.

Static fields belong to a class and are not Serialized;
transient members are also ignored for Serialization

Inheritance and Composition

if a class implements Serializalble, all its sub-classes are as well;
if an object has reference to another object within it, these must implement seperately, else NotSerializableException

serialVersionUID

must be static, final and type long also keep it private to avoid being inherited.

JVM associates version (long) numer with each serializable class.
used to verify saved and loaded objects are compatible;
based on class name, attributes and access modifiers;
throws InvalidClassException
if not declared generated at runtime

Why avoid implicit compiler generated UID :
Changing when it shouldn’t may happen for reasons other than class layout changes - the problem is that it’s compiler implementation dependent. If you do debug with Eclipse but do production builds with javac, you may end up with two incompatible sets of data.

Why serialize Exception class?

Your exception classes should always be serializable . You have no idea where the exception might be used, and if it gets marshaled across an app domain, you may lose debugging information or even lose the entire exception altogether. Exceptions are intended to be usable anywhere, and if they’re not serializable, you can’t use them across app domains.

The same principles also apply to C# exceptions.


References

Baeldung
Geeks4Geeks Serialization in Java