Variable initialization past Xstream

Go To StackoverFlow.com

3

Consider the following declaration as part of SomeClass

private Set<String> blah    = new HashSet<String>();

Made in a class, which is later

XStream xstream = new XStream(new JettisonMappedXmlDriver());
xstream.setMode(XStream.NO_REFERENCES);

StringBuilder json = new StringBuilder(xstream.toXML(SomeClass));

rd = (SomeClass) xstream.fromXML(json.toString());

When i @Test

assertTrue(rd.getBlah().size() == 0);

I get an NPE on rd.getBlah()

When I, instead of initializing up front, place initialization to a constructor of SomeClass

public SomeClass() {
  blah = new HashSet<String>();
}

Same problem - NPE on rd.getBlah()

When i modify the getter to check for null first, it works, but ..

public Set<String> getBlah() {
   if (blah == null)
      return new HashSet<Sgring>();
   return blah;
}

I am puzzled ... Why does XStream not initialize variables and whether lazy instantiation is necessary?

2012-04-04 22:27
by JAM
I am a little confused by xstream.toXML(SomeClass); Shouldn't it be xstream.toXML(object) where object is of type SomeClass - Max 2012-04-04 22:32
If there is anything we know it is that SomeClass is most certainly of type SomeClass : - JAM 2012-04-05 00:16
My point was: taking what you've written above at face value, if SomeClass is a type, then your code above does not compile. SomeClass is not of type SomeClass, and neither is SomeClass.class of type SomeClass.. - Max 2012-04-05 01:23


5

XStream uses the same mechanism as the JDK serialization. When using the enhanced mode with the optimized reflection API, it does not invoke the default constructor. The solution is to implement the readResolve method as below:

public class SomeClass{
    private Set<String> blah;

    public SomeClass(){
        // do stuff
    }

    public Set<String> getBlah(){
        return blah;
    }

    private Object readResolve() {
        if(blah == null){
            blah = new HashSet<String>();
        }
        return this;
    }
}

Reference

2012-04-04 22:34
by mre
Thank you. Indeed this works!. Two things: could you provide a reference to the above and how may i find out whether i am running in enhanced mode or not - JAM 2012-04-04 22:37
@JAM, 1) I provided the reference below the code snippet and 2) I am not sure, but I believe it runs in this mode by default. - mre 2012-04-04 22:39
Why does readObject() not work in this instance? I have a similar problem here: http://stackoverflow.com/questions/15752945/xstream-wont-call-readobject in which readObject() seems to be the right solution, but only readResolve() works - eipark 2013-04-02 13:33
Ads