Trail: JavaBeans(TM)

Lesson: Long Term Persistence

Long-term persistence is a model that enables beans to be saved in XML format.

Information on the XML format and on how to implement long-term persistence for non-beans can be found in XML Schemaand Using XMLEncoder.

Encoder and Decoder

The XMLEncoderclass is assigned to write output files for textual representation of Serializable objects. The following code fragment is an example of writing a Java bean and its properties in XML format:

     XMLEncoder encoder = new XMLEncoder(
                new BufferedOutputStream(
                        new FileOutputStream( "Beanarchive.xml" ) ) );

        encoder.writeObject( object );
        encoder.close(); 

The XMLDecoderclass reads an XML document that was created with XMLEncoder:

      XMLDecoder decoder = new XMLDecoder(
                new BufferedInputStream(
                        new FileInputStream( "Beanarchive.xml" ) ) );

        Object object = decoder.readObject();
        decoder.close();

What's in XML?

An XML bean archive has its own specific syntax, which includes the following tags to represent each bean element:

The following code represents an XML archive that will be generated for the SimpleBean component:

<?xml version="1.0" encoding="UTF-8" ?>
<java>
  <object class="javax.swing.JFrame">
    <void method="add">
      <object class="java.awt.BorderLayout" field="CENTER"/>
      <object class="SimpleBean"/>
    </void>
    <void property="defaultCloseOperation">
      <object class="javax.swing.WindowConstants" field="DISPOSE_ON_CLOSE"/>
    </void>
    <void method="pack"/>
    <void property="visible">
      <boolean>true</boolean>
    </void>
  </object>
</java>

Problems with the examples? Try Compiling and Running the Examples: FAQs.
Complaints? Compliments? Suggestions? Give us your feedback.

Previous page: Previous Lesson
Next page: Introspection