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