![]() |
The Java Developers Almanac 1.4Order this book from Amazon. |
e7. Serializing a Bean to XMLTheXMLEncoder class serializes an object in similar fashion to
java.io.ObjectOutput . However, unlike ObjectOutput , which
persists all non-transient private and public data, the
XMLEncoder only persists the value of public properties. In
particular, for every public property, XMLEncoder calls its
getter method and persists the returned value. In deserialization, a
newly created object is initialized with these persisted property
values. Therefore, any private state that is not associated with a
property will, by default, not be persisted.
See also e8 Deserializing a Bean from XML. // Create an object and set properties MyClass o = new MyClass(); o.setProp(1); o.setProps(new int[]{1, 2, 3}); try { // Serialize object into XML XMLEncoder encoder = new XMLEncoder(new BufferedOutputStream( new FileOutputStream("outfilename.xml"))); encoder.writeObject(o); encoder.close(); } catch (FileNotFoundException e) { } // This class defines two properties - prop and props public class MyClass { // The prop property int i; public int getProp() { return i; } public void setProp(int i) { this.i = i; } // The props property int[] iarray = new int[0]; public int[] getProps() { return iarray; } public void setProps(int[] iarray) { this.iarray = iarray; } }Here is the XML data: <?xml version="1.0" encoding="UTF-8"?> <java version="1.4.0" class="java.beans.XMLDecoder"> <object class="MyClass"> <void property="prop"> <int>1</int> </void> <void property="props"> <array class="int" length="3"> <void index="0"> <int>1</int> </void> <void index="1"> <int>2</int> </void> <void index="2"> <int>3</int> </void> </array> </void> </object> </java>
e9. Preventing a Bean Property from Being Serialized to XML e10. Serializing an Immutable Bean Property to XML
© 2002 Addison-Wesley. |