Java Reference
In-Depth Information
size versus ease of use). See https://github.com/eishay/jvm-serial-
izers/wiki/ .
For a class to be serializable, it needs to implement the Serializable interface,
which is a Marker interface : it doesn't have any methods, but instead tells the serializa-
tion mechanism that you have allowed the ability of your class to be serialized. While
not evident from the onset, serialization exposes all the internal workings of your class
(including protected and private members), so if you want to keep secret the authoriza-
tion code for a nuclear launch, you might want to make any class that contains such in-
formation nonserializable.
It is also necessary that all properties (a.k.a. members, variables, or fields) of the
class are serializable (and/or transient, which we will get to in a minute). All primit-
ives— int , long , double , and float (plus their wrapper classes)—and the
String class, are serializable by design. Other Java classes are serializable on a case-
by-case basis. For example, you can't serialize any Swing components (like JBut-
ton or JSpinner ), and you can't serialize File objects, but you can serialize the
Color class ( awt.color , to be more precise).
As a design principle you don't want to serialize your main classes, but instead you
want to create classes that contain only the properties that you want to serialize. It will
save a lot of headache in debugging because serialization becomes very pervasive. If
you mark a major class as serializable ( implements Serializable ), and this
class contains many other properties, you need to declare those classes as serializable
as well. If your Java class inherits from another class, the parent class must also be
serializable. In that way, you will find marking classes serializable when they really
shouldn't be.
If you want to mark a property as nonserializable, you may mark it as transient .
Transient properties tell the Java compiler that you are not interested in saving/loading
the property value, so it will be ignored. Some properties are good candidates for being
transient, like cached calculations, or a date formatter that you always instantiate to the
same value.
By the virtue of the Serialization framework, static properties are not serializable;
neither are static classes. The reason is that a static class cannot be instantiated.
Therefore, if you save and then load the static class at the same time, you will have
loaded another copy of the static class, throwing the JVM for a loop.
The Java serialization mechanism works behind the scenes to convert and traverse
every object within the class that is marked as Serializable . If an application con-
Search WWH ::




Custom Search