Java Reference
In-Depth Information
How It Works
XMLEncoder and XMLDecoder , like the Serialization framework, use reflection to
determine which fields are to be written, but instead of writing the fields as binary, they
are written as XML. Objects that are to be encoded do not need to be serializable, but
they do need to follow the Java Beans specification.
Java Bean is the name of any object that conforms to the following contract:
The object contains a public empty ( no-arg ) constructor.
The object contains public getters and setters for each protected/private
property that takes the name of get{Property}() and
set{Property}() .
The XMLEncoder and XMLDecoder will encode/decode only the properties of
the Bean that have public accessors ( get{property}, set{property} ), so any
properties that are private and do not have accessors will not be encoded/decoded.
Tip It is a good idea to register an Exception Listener when encoding/decoding.
The XmlEncoder creates a new instance of the class that being serialized (re-
member that they need to be Java Beans, so they must have an empty no-arg con-
structor), and then figures out which properties are accessible (via get{property},
set{property} ). And if a property of the newly instantiated class contains the
same value as the property of the original class (i.e., has the same default value), the
XmlEncoder doesn't write that property. In other words, if the default value of a
property hasn't changed, the XmlEncoder will not write it out. This provides the
flexibility of changing what a “default” value is between versions. For example, if the
default value of a property is 2 when an object is encoded, and later decoded after the
default property changed from 2 to 4, the decoded object will contain the new default
property of 4 (which might not be correct).
The XMLEncoder also keeps track of references. If an object appears more than
once when being persisted in the object graph (for example, an object is inside a Map
from the main class, but is also as the DefaultValue property), then the XMLEn-
coder will only encode it once, and link up a reference by putting a link in the xml.
The XMLEncoder / XMLDecoder is much more forgiving than the Serialization
framework. When decoding, if a property type is changed, or if it was deleted/added/
Search WWH ::




Custom Search