Search code examples
javaserializationdeserializationxstream

XStream won't call readObject()


I have code that is modeled as such:

class A {
    private transient Foo foo = new Foo();
    private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
        in.defaultReadObject();
        foo = new Foo();
    }
}

class B extends A {}

I added readObject() to A so that during deserialization, the transient foo will be initialized. However, I stuck breakpoints in my code and could see that XStream is not calling readObject() at all. I also tried sticking readObject() in class B that calls an initFoo() function in A, and that didn't work either.

The FAQ on the website does not seem to imply any other boilerplate is necessary for this to work. Why is it not being called?


Solution

  • It seems that the XStream documentation was incorrect, or at least misleading. It says in http://x-stream.github.io/faq.html#Serialization_initialize_transient,

    Use the latter [readObject] in class hierarchies, readResolve is not called for base classes.

    However, replacing readObject() with readResolve() in the code I listed in my question, it seems to be called and foo is being initialized properly. This is confusing though because according to documentation of both XStream and java.io.Serializable, readObject() seems to be what I need.

    The breakpoint inside the method still is not being hit however. It may have to do with the way these Serializable methods are being called.