Selena Selena -4 years ago 134
Java Question

Is there an equivalent of the Jackson HandlerInstantiator in JaxB?

I am a JaxB noob, but I've learned a lot about how to configure Jackson. I am adding XML serialization/deserialization support for some domain object classes. I have a class type that is serialized/deserialized differently depending on a context which must be specified.

I was able to accomplish this in Jackson by writing a custom implementation of

HandlerInstantiator
. The custom implementation takes the context as a constructor parameter. When a serializer or deserializer is required for these context sensitive objects, the method that provides it instantiates it with the context the handler was constructed with. I wrote a service class for my library that the user can use to request an object mapper configured for the desired context.

In this way, I am still able to use the
@JsonSerialize
and
@JsonDeserialize
annotations on the fields that are affected by this context sensitive behavior even though I need to instantiate these classes with non-default constructors.

So, is there something similar that I can do in JaxB, so that I can write generic
XmlAdapters
that will take the context as a parameter for their constructors? By default, JaxB, like Jackson, requires a no-arg constructor for the adapters. I was hoping there was something similar to the Jackson
InstantiatorHandler
that I can override and then somehow configure JaxB to use in a similar fashion.

Answer Source

You can bind any XmlAdapter class to a concrete instance. Both JAXB Marshaller/Unmarshaller interfaces provide method setAdapter

Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
unmarshaller.setAdapter(new MyClassXmlAdapter(...));

Now all fields/types annotated with @XmlJavaTypeAdapter will be adapted with given instance

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download