|
|
Writing a Simple Bean |
For complete information on persistence and serialization, see the Object Serialization web site.
A Bean persists by having its properties, fields, and state information saved and restored to and from storage. The mechanism that makes persistence possible is called serialization. When a Bean instance is serialized, it is converted into a data stream and written to storage. Any applet, application, or tool that uses that Bean can then "reconstitute" it by deserialization. JavaBeans uses the JDK's Object Serialization API for its serialization needs.
As long as one class in a class's inheritance hierarchy implements Serializable or Externalizable, that class is serializable.
All Beans must persist. To persist, your Beans must support serialization by implementing either the java.io.Serializable interface, or the java.io.Externalizable interface. These interfaces offer you the choice between automatic serialization, and "roll your own".
Controlling Serialization
You can control the level of serialization that your Beans undergo:
- Automatic: implement
Serializable. Everything gets serialized.- Selectively exclude fields you do not want serialized by marking with the
transient(orstatic) modifier- Writing Beans to a specific file format: implement
Externalizable, and its two methods.Default Serialization: The
SerializableInterfaceThe
Serializableinterface provides automatic serialization by using the Java Object Serialization tools.Serializabledeclares no methods; it acts as a marker, telling the Object Serialization tools that your Bean class is serializable. Marking your class withSerializablemeans you are telling the Java Virtual Machine (JVM) that you have made sure your class will work with default serialization. Here are some important points about working with theSerializableinterface:
- Classes that implement
Serializablemust have a no-argument constructor. This constructor will be called when an object is "reconstituted" from a .ser file.- There is no need to implement
Serializablein your class if if it is already implemented in a superclass.- All fields but static and transient are serialized. Use the
transientmodifier to specify fields you do not want serialized, and to specify classes that are not serializable.The BeanBox writes serialized Beans to a file with a .ser extension.
The OurButton demo Bean uses default serialization to make its properties persist. OurButton only added
Serializableto its class definition to make use of default serialization:public class OurButton extends Component implements Serializable,...If you drop an
OurButtoninstance into the BeanBox, the properties sheet displays OurButton's properties. To ascertain that serialization is workingThe
- Change some OurButton properties. For example change the font size and colors.
- Serialize the changed OurButton instance by selecting the File|SerializeComponent... BeanBox menu item. A file browser will pop up.
- Put the .ser file in a JAR file with a suitable manifest (need to explain how to do this).
- Clear the BeanBox form by selecting the File|Clear menu item.
- Reload the serialized instance by selecting the File|LoadJar menu item.
OurButtoninstance will appear in the BeanBox with your property changes intact. By implementingSerializablein your class, simple, primitive properties and fields can be serialized. For more complex class members, different techniques must be used.Selective Serialization Using the
transientKeywordTo exclude fields from serialization in a
Serializableobject from serialization, mark the fields with thetransientmodifier.transient int Status;Default serialization will not serializetransientandstaticfields.Selective Serialization:
writeObjectandreadObject()If your serializable class contains either of the following two methods (the signatures must be exact), then the default serialization will not take place.
private void writeObject(java.io.ObjectOutputStream out) throws IOException; private void readObject(java.io.ObjectInputStream in) throws IOException, ClassNotFoundException;You can control how more complex objects are serialized, by writing your own implementations of the
writeObject()andreadObject()methods. ImplementwriteObjectwhen you need to exercise greater control over what gets serialized, when you need to serialize objects that default serialization cannot handle, or when you need to add data to the serialization stream that is not an object data member. ImplementreadObject()to reconstruct the data stream you wrote withwriteObject().Example: The
MoleculeDemo BeanThe
Moleculedemo keeps a version number in a static field. Since static fields are not serialized by default,writeObject()andreadObject()are implemented to serialize this field. Here is thewriteObject()andreadObject()implementations inMolecule.java:private void writeObject(java.io.ObjectOutputStream s) throws java.io.IOException { s.writeInt(ourVersion); s.writeObject(moleculeName); } private void readObject(java.io.ObjectInputStream s) throws java.lang.ClassNotFoundException, java.io.IOException { // Compensate for missing constructor. reset(); if (s.readInt() != ourVersion) { throw new IOException("Molecule.readObject: version mismatch"); } moleculeName = (String) s.readObject(); }These implementations limit the fields serialized to
ourVersionandmoleculeName. Any other data in the class will not be serialized.It is best to use the
ObjectInputStream'sdefaultWriteObject()anddefaultReadObjectbefore doing your own specific stream writing. For example:private void writeObject(java.io.ObjectOutputStream s) throws java.io.IOException { //First write out defaults s.defaultWriteObject(); //... } private void readObject(java.io.ObjectInputStream s) throws java.lang.ClassNotFoundException, java.io.IOException { //First read in defaults s.defaultReadObject(); //... }The
ExternalizableInterfaceUse the
Externalizableinterface to when you need complete control over your Bean's serialization (for example, when writing and reading a specific file format). You need to implement two methods:readExternal()andwriteExternal().Externalizableclasses must also have a no-argument constructor.Example: The
BlueButtonandOrangeButtonDemo BeansWhen you run the BeanBox, you will see two Beans named
BlueButtonandOrangeButtonin the ToolBox. These two Beans are actually serialized instances of theExternalizableButtonclass.
ExternalizableButtonimplements theExternalizableinterface. This means it does all its own serialization, by implementingExternalizable.readExternal()andExternalizable.writeExternal(). TheBlueButtonWriterprogram is used by the buttons makefile to create anExternalizableButtoninstance, change itsbackgroundproperty to blue, and write the Bean out to the fileBlueButton.ser.OrangeButtonis created the same way, usingOrangeButtonWriter. The button makefile then puts these.serfiles inbuttons.jar, where the ToolBox can find and reconstitute them.
|
|
Writing a Simple Bean |