假设我们有一个类 Test 像:
public class Test {
private final String name;
private final List<String> list = new ArrayList<>();
public Test(String name) {
this.name = name;
}
void add(String s) {
list.add(s);
}
void print() {
System.out.println("name: " + name);
for (String s : list) {
System.out.println(" - " + s);
}
}
}
没有 XSteam 的不变量
this.list != null
每次都持有。
但是如果我们看一下第四个测试
public static void main(String[] args) {
final XStream xstream = new XStream();
xstream.alias("test", Test.class);
// Serialize
final Test test1 = new Test("XYZ");
test1.add("One");
test1.add("Two");
//@formatter:off
/* name: XYZ
* - One
* - Two
*/
//@formatter:on
test1.print();
//@formatter:off
/* <test>
* <name>XYZ</name>
* <list>
* <string>One</string>
* <string>Two</string>
* </list>
* </test>
*/
//@formatter:on
System.out.println(xstream.toXML(test1));
// Deserialize with one list entry
final String xmlTest2 = "<test><name>XYZ</name><list><string>One</string></list></test>";
final Test test2 = (Test) xstream.fromXML(xmlTest2);
//@formatter:off
/* <test>
* <name>XYZ</name>
* <list>
* <string>One</string>
* </list>
* </test>
*/
//@formatter:on
test2.print();
// Deserialize with empty list
final String xmlTest3 = "<test><name>XYZ</name><list /></test>";
final Test test3 = (Test) xstream.fromXML(xmlTest3);
//@formatter:off
/* name: XYZ
*/
//@formatter:on
test3.print();
// Deserialize without list-tag
final String xmlTest4 = "<test><name>XYZ</name></test>";
final Test test4 = (Test) xstream.fromXML(xmlTest4);
//@formatter:off
/* name: XYZ
* Exception in thead ... NullPointerException
*/
//@formatter:on
test4.print();
}
我们看到一个 NullPointerException,因为list
没有初始化。
我想list
在 XML 可选中包含与 test4 类似的 -element。我能做些什么?因为我的数据模型中有很多类类似于Test
,所以我不想Converter
为每个类都写一个。但是假设我会写一个Converter
,我该如何设置最终属性name
?