tags:

views:

202

answers:

2

I am using nice little piece of xstream to perform serialization.

I have the following class :

// version 0
class A {
}

// version 1
class A {
    Object o = new Object();
}

In order for me to read version 0 xml file to construct version 1 class A, I will have to add the following method in version 1 class A :

class A {
    private Object readResolve() 
    { 
        /* For backward compatible */ 
        if (o == null) { o = new Object(); }
    }
    Object o = new Object();
}

This works fine so far.

Now, the situation is being reversed.

I have the following class :

// version 0
class A {
    Object o = new Object();
}

// version 1
class A {
}

How can I able to make reading xml file version 0, to construct class A version 1?

Here is the exception you are going to get, if you try to do so :

run:
com.thoughtworks.xstream.converters.ConversionException: a : a
---- Debugging information ----
message             : a : a
cause-exception     : com.thoughtworks.xstream.mapper.CannotResolveClassException
cause-message       : a : a
class               : javaapplication15.Main$A
required-type       : javaapplication15.Main$A
path                : /javaapplication15.Main$A/a
line number         : 2
-------------------------------
null
BUILD SUCCESSFUL (total time: 2 seconds)
A: 

You could register a custom converter for Class A, which gives you control over the msrshalling and unmarshalling. It's a pretty heavyweight solution, though, and makes XStream rather less attractive.

It's because of cases like this that I tend to avoid XStream for everything other than very trivial situations, and never for situations where the XML might be persisted beyond the lifetime of the running application. It's just too fragile (and buggy). A more robust marshalling framework would be by choice, even if they take more up-front effort to configure.

skaffman
"You could register a custom converter for Class A" -> Can you describe in more detail? This statement is too abstract for me.
Yan Cheng CHEOK
The XStream class allows you to register converters which tell it how to convert objects to and from XML. You could write one which knows how to handle objects of Class A.
skaffman
A: 

Currently, I am having backward compatible using the following strategy :

// version 0
class A {
    Object o = new Object();
}

// version 1
class A {
    // This will ensure o will not be be read, or be written into file. 
    // transient keyword which prevent read, will only work well for xstream 1.3.1
    transient Object o = new Object();
}

// version 2. Slowly phase out Object o, after class A had been deployed for quite sometime.
class A {
}
Yan Cheng CHEOK