📄 e010. serializing an immutable bean property to xml.txt
字号:
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>
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -