This project provides the code samples for the CodeFX post about serializing Optional
. It demonstrates how an Optional
instance can be (de)serialized using different approaches.
For fields it shows how it fails and how it is done correctly. It provides a class SerializableOptional
, which wraps an Optional
for serialization (e.g. for RMI) and some classes using it. Finally, it provides a demo which ties it all together.
The classes ClassUsingOptional
and ClassUsingOptionalCorrectly
each contain a field with type Optional
. While the first fails at serialization (using the default serialization mechanism), the second does not (because it properly implements the serialization proxy pattern).
The SerializableOptional
is a simple wrapper for an Optional
which implements Serializable
.
The comment on SerializableOptional
describes different approaches on how to use it to serialize a class with an optional field. The classes TransformFor...
show examples for these approaches.
That Optional
is not serializable is no mere oversight. The reasons are described in all detail in a blog post from CodeFX. The gist is:
Optional
was only meant for return values, so there is no need to serialize it.- Making a class serializable heavily reduces the flexibility to change it later.
Optional
is a value-based class and those should not be serialized.