Serializing an Immutable Bean Property to XML

An immutable property is one where the value is supplied to the constructor rather than through a setter method. By default, immutable properties are not persisted. This example demonstrates how to persist an immutable property called prop.
// Create an object with an immutable property and set the value // of the immutable property in the constructor MyClass3 o = new MyClass3(123); try { // Create the encoder XMLEncoder encoder = new XMLEncoder(new BufferedOutputStream( new FileOutputStream("outfilename.xml"))); // Specify to the encoder, the name of the property that is associated // with the constructor's parameter(s) String[] propertyNames = new String[]{"prop"}; encoder.setPersistenceDelegate(MyClass3.class, new DefaultPersistenceDelegate(propertyNames); // Serialize the object into XML encoder.writeObject(o); encoder.close(); } catch (FileNotFoundException e) { }
// This class defines an immutable property called prop. // The value of the immutable property is initialized import java.beans.*; public class MyClass3 { int prop; // The constructor that initializes the immutable property prop public MyClass3(int prop) { this.prop = prop; } // The immutable property public int getProp() { return prop; } }
Here is the XML data:
<?xml version="1.0" encoding="UTF-8"?> <java version="1.4.0" class="java.beans.XMLDecoder"> <object class="MyClass3"> <int>123</int> </object> </java>

Post a comment

More information about formatting options

CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.
Image CAPTCHA
Enter the characters shown in the image. Ignore spaces and be careful about upper and lower case.