Note that there are some explanatory texts on larger screens.

plurals
  1. PODeserialize a final list attribute
    text
    copied!<p>Suppose we have a class Test like:</p> <pre><code>public class Test { private final String name; private final List&lt;String&gt; list = new ArrayList&lt;&gt;(); 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); } } } </code></pre> <p>Without XSteam the invariant</p> <pre><code>this.list != null </code></pre> <p>holds every time.</p> <p>But if we look in the 4th test in</p> <pre><code>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 /* &lt;test&gt; * &lt;name&gt;XYZ&lt;/name&gt; * &lt;list&gt; * &lt;string&gt;One&lt;/string&gt; * &lt;string&gt;Two&lt;/string&gt; * &lt;/list&gt; * &lt;/test&gt; */ //@formatter:on System.out.println(xstream.toXML(test1)); // Deserialize with one list entry final String xmlTest2 = "&lt;test&gt;&lt;name&gt;XYZ&lt;/name&gt;&lt;list&gt;&lt;string&gt;One&lt;/string&gt;&lt;/list&gt;&lt;/test&gt;"; final Test test2 = (Test) xstream.fromXML(xmlTest2); //@formatter:off /* &lt;test&gt; * &lt;name&gt;XYZ&lt;/name&gt; * &lt;list&gt; * &lt;string&gt;One&lt;/string&gt; * &lt;/list&gt; * &lt;/test&gt; */ //@formatter:on test2.print(); // Deserialize with empty list final String xmlTest3 = "&lt;test&gt;&lt;name&gt;XYZ&lt;/name&gt;&lt;list /&gt;&lt;/test&gt;"; final Test test3 = (Test) xstream.fromXML(xmlTest3); //@formatter:off /* name: XYZ */ //@formatter:on test3.print(); // Deserialize without list-tag final String xmlTest4 = "&lt;test&gt;&lt;name&gt;XYZ&lt;/name&gt;&lt;/test&gt;"; final Test test4 = (Test) xstream.fromXML(xmlTest4); //@formatter:off /* name: XYZ * Exception in thead ... NullPointerException */ //@formatter:on test4.print(); } </code></pre> <p>we see a NullPointerException, because <code>list</code> was not initialized.</p> <p>I'd like to have the <code>list</code>-element in the XML optional similiar to test4. What can I do? Because there are many classes in my datamodel similiar to <code>Test</code>, I don't want to write a <code>Converter</code> for every class. But suppose I would write a <code>Converter</code>, how can I set the final attribute <code>name</code>?</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload