clapsus
clapsus

Reputation: 462

Add unmarshalling method to JAXB generated POJOs

I have a bunch of XSDs that i transform into POJO with the jaxb maven plugin.

For logging purposes, i'd like to have a "unmarshal" method directly integrated inside the JAXB objects, so that i could call something like generatedPOJO.toXMLString(), knowing that generatedPOJO is the POJO generated from the XSD file via JAXB.

I tried to look in the Custom bindings documentation, but i got nothing out of that.

Thank you for your help.

EDIT: What i want is that JAXB, in addition to generating POJOs from XSD files, adds a toXMLString() method to these POJOs.

This method needs to be generated by JAXB, since i can't edit the generated POJOS.

Upvotes: 0

Views: 437

Answers (1)

lexicore
lexicore

Reputation: 43651

In short, don't do this, it won't be a good design.

While, as @j.con pointed out, it is possible to add further methods to the generated classes, using -xinject-code or a custom XJC plugin, adding a marshalling method is not a good idea. With JAXB API, it will be pretty ugly.

To do anything you'll need an instance of JAXBContext. Either you'll pass it to your method or instantiate within the method.

The latter isn't quite good as JAXBContext is instantiated for a collection of classes or packages (context path). So you'll basically have to preset, with which classes your class may be used together. Doing so, you're losing flexibility.

Next, JAXB marshallers produce many things, not just strings/stream results but also DOM or SAX or StAX. JAXB API is quite cool about that. Opting just for strings seems to be a shortsighted choice to be.

Finally, I don't think adding toXMLString() or whatever is so much sweet syntactic sugar compared to a simple utility service or class. And hacking into code generation for that really feels like misplaced effort.

Upvotes: 2

Related Questions