![]() |
The Java Developers Almanac 1.4 |
|
e10. Serializing an Immutable Bean Property to XMLAn 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 calledprop.
// 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>
e8. Deserializing a Bean from XML e9. Preventing a Bean Property from Being Serialized to XML
© 2002 Addison-Wesley. |