|
Preventing Serialization Custom Serialization
| |
Not every item in a class object can, or should be,
serialized. Here are some of the issues:
- Some objects are inherently specific to the program's
execution state, and would have no meaning elsewhere.
For
example, a FileDescriptor
object would have no meaning outside of the program
that was using it. Especially on another machine or
operating system architecture!
Another example is a GUI-based class that retains
knowledge of its size based on a calculation
previously performed using knowledge of local font
sizes. Since font sizes vary from machine to machine,
this piece of state would not be useful on another
machine.
Yet another example: A class that obtains some
platform-specific information, such as is available
from the system properties. This information should
not be serialized out, even if it is only to be used
on the same machine type. This is because things may
change, even on the same machine: the JDK version may
change; the user's default directory may change, or
even the operating system may change.
- Some object state is sensitive, and should not be
made available outside of its security domain.
For
example, a password should not typically be
serialized, except in an encrypted form.
- Some classes are constructed in a way that guarantees
their validity. Serialization provides an opportunity
to subvert such guarantees.
For example, a Date
object might be constructed in such a way as to make
a date of 31 February 1999
impossible. However, if that object were serialized
out to a file, and the file was subsequently tampered
with, such an invalid date could be created as a
result of serializing it back into memory.
For these reasons, classes are not Serializable by
default. However, what if we wish a class to be Serializable,
but it contains items with such problems?
There are two possible solutions:
- We could prevent the sensitive items from being
serialized out.
- We could allow the sensitive items to be serialized
out, but in some special form that does not present
any of the above problems.
|