O'Reilly logo

Java Examples in a Nutshell, 3rd Edition by David Flanagan

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Custom Serialization

Not every piece of program state can, or should be, serialized. Such things as FileDescriptor objects are inherently platform-specific or virtual machine-dependent. If a FileDescriptor were serialized, for example, it would have no meaning when deserialized in a different virtual machine. For this reason, and also for the important security reasons described earlier, not all objects can be serialized.

Even when an object is serializable, it may not make sense for it to serialize all its state. Some fields may be "scratch" fields that can hold temporary or precomputed values but don't actually hold state needed to restore a serialized object. Consider a GUI component. It may define fields that store the coordinates of the last mouse click it received. This information is never of interest when the component is deserialized, so there's no need to bother saving the values of these fields as part of the component's state. To tell the serialization mechanism that a field shouldn't be saved, simply declare it transient:

protected transient short last_x, last_y; // Temporary fields for mouse pos

There are also situations where a field is not transient (i.e., it does contain an important part of an object's state), but for some reason it can't be successfully serialized. Consider another GUI component that computes its preferred size based on the size of the text it displays. Because fonts have slight size variations from platform to platform, this precomputed preferred ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required