Developing Java Beans 5.2.1 Static Data Members Static
Developing Java Beans 5.2.1 Static Data Members Static data members are not serialized automatically. Only the data associated with a specific instance of the class is serialized. If you want to serialize data stored in a static variable, you’ll have to provide class-specific serialization. We’ll look at the technique for doing so a little later. Data members that are marked as static final are considered to be part of the class definition, so they don’t have to be saved during serialization. In fact, it would be impossible to set their values during deserialization, since they are marked as final. 5.2.2 Transient Data Members Some data members may not be a part of the persistent state of the object. Classes may define data members for use as scratch variables, or to make some other part of their processing easier. It may be unnecessary, or even inappropriate, to serialize these data members. For instance, you might include some data members to keep run-time statistics on your object. These statistics may, for example, keep track of how many times a particular property is accessed. This is not the kind of data you want to serialize since it is not part of the persistent state of the object you wouldn’t want to restore that information when the object is reconstructed. These data members should be marked with the transient modifier. The standard object serialization mechanism will not save and restore data members that are marked as transient. It is also necessary to use the transient modifier on data members that are instances of classes that are not serializable. As I mentioned above, a java.io.NotSerializableException will be thrown when an attempt is made to save or restore an instance of a class that is not serializable. If this happens, the serialization process won’t complete. However, it’s not as simple as marking a data member as transient. After all, this data may represent all or part of the state of the object. We’ll examine this problem more closely a little later when we look at how the GenericButtonAdapter from an earlier chapter interacts with the serialization process. 5.2.3 Implementing Serialization Let’s look at the following example: public class SimpleExample implements java.io.Serializable { protected int anInteger; protected float aFloat; protected java.awt.Button aButton; public SimpleExample() { } } The class SimpleExample contains three data members. The first two, anInteger and aFloat, are primitive data types. As we discussed earlier, all primitive data types are automatically serializable. The data member called aButton is an instance of type java.awt.Button. This is a subclass of java.awt.Component, which itself implements java.io.Serializable. So the SimpleExampleclass can be serialized without doing anything more than declaring that it implements the java.io.Serializable interface. page 74