![]() |
The Java Developers Almanac 1.4Order this book from Amazon. |
e9. Preventing a Bean Property from Being Serialized to XMLBy default, when serializing an object into XML, the current value of all public properties is persisted (if they don't equal the default value). This example demonstrates how to prevent a public property from being persisted.See also e8 Deserializing a Bean from XML. // Create an object and set properties MyClass2 o = new MyClass2(); o.setProp(1); o.setProps(new int[]{1, 2, 3}); try { // Serialize object into XML. // props is transient so it will not be persisted. 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. // The props property is marked transient so that it will not // be persisted if serialized into XML. import java.beans.*; public class MyClass2 { // 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; } static { try { // Make the props property transient BeanInfo info = Introspector.getBeanInfo(MyClass2.class); PropertyDescriptor[] propertyDescriptors = info.getPropertyDescriptors(); for (int i = 0; i < propertyDescriptors.length; ++i) { PropertyDescriptor pd = propertyDescriptors[i]; if (pd.getName().equals("props")) { pd.setValue("transient", Boolean.TRUE); } } } catch (IntrospectionException e) { } } }Here is the XML data: <?xml version="1.0" encoding="UTF-8"?> <java version="1.4.0" class="java.beans.XMLDecoder"> <object class="MyClass2"> <void property="prop"> <int>1</int> </void> </object> </java>
e8. Deserializing a Bean from XML e10. Serializing an Immutable Bean Property to XML
© 2002 Addison-Wesley. |