A class is defined with the following JAXB annotation:
class Course {
@XmlElement (name = "book")
List<Book> requiredBooks = new ArrayList<Book>();
When unmarshalling an XML document that contains this
<course>
...
<book/>
</course>
I end up with a Book added to the list, with all of its attributes set to null. I don’t control the XML input. How can I prevent this empty book from being added? I tried intercepting in set..() or add..() methods, but turns out JAXB bypasses setters when dealing with collections. Any suggestions?
Here’s a solution that does work. Again, elegance was left behind.
There are two callbacks defined by JAXB: beforeUnmarshal and afterUnmarshal. By implementing afterUnmarshal to clean up the list, I was able to achieve the desired result.
While this works, by biggest issue with it is the absence of an interface for implementing afterUnmarshal. It’s looked up by JAXB using reflection, but I think it would’ve been convenient (and would reduce debugging/maintenance) if JAXB simply supplied interfaces and/or absract implementations. As it is, what if the signature of afterUnmarshal changes in the future? This code will just mysteriously stop working as it’s supposed to.