Saturday, June 7, 2008

JAXB and Collections

Am I missing something? Does JAXB really require you to expose a naked collection in mapped objects?

If I expose a Collections.unmodifiableSet(property), JAXB invokes .clear(), which throws an UnsupportedOperationException.

If I return a shallow copy of the collection, when JAXB is converting XML to Java, JAXB requests the collection, clears it and modifies it, without so much as calling the setter again. As a result, the collection values don't appear in the final Java object.

That seems pretty awkward, so my first assumption is that I've made a mistake somewhere along the line, but ... perhaps JAXB really does want me to expose a mutable object, with the risk that entails. :/

3 comments:

Unknown said...

Have you taken a look at javax.xml.bind.annotation.XmlAccessorType? I allows several different ways for JAXB to access your info. If you like, you can use protected or private accessor methods for your collections. You can also instruct JAXB to serialize directly from fields.

Geoffrey Wiseman said...

I've tried using JAXB directly on fields, but it created some other problems for me -- JAXB seems ok with serializing a Map from a method, but not from a field -- I haven't experimented at length with that yet, though.

Anonymous said...

I think you are right, i have found the draft specification which states under 4.5.2.2 "List Property" that there is only a getter for List based properties, because the list is part of the object itself and adding and removing elements from the list is the same as altering the objects state directly. Unbelievable, I thought so too, see for yourself http://xml.coverpages.org/jaxb-V07spec.pdf