JAXB XML Adapters work via annotations but not via setAdapter JAXB XML Adapters work via annotations but not via setAdapter xml xml

JAXB XML Adapters work via annotations but not via setAdapter


The setAdapter(XmlAdapter) on Marshaller is used to pass in an initialized XmlAdapter for a property that is already annotated with @XmlJavaTypeAdapter. The link below is to an answer where I leverage this behaviour:

If you want to map third party classes you could use EclipseLink JAXB (MOXy)'s XML mapping file (I'm the MOXy lead):


You always have to annotate with @XmlJavaTypeAdapter(...).

marshaller.setAdapter(...) is means to assign a custom initialized instance of your type adapter in case you have non default constructor initialisation.

Otherwise, if you have only one default constructor for your adapter, then you don't need to explicitly call .setAdapter(...) method.

Here is a great answer with more detailed explanation:JAXB: Isn't it possible to use an XmlAdapter without @XmlJavaTypeAdapter?

JAXB Runtime can only accept Adapter with No-args constructor .. (Obviously JAXBContext does not know about application specific model)

So thankfully there is an option :D

You can tell your unmarshaller to use given instance of UserAdapter rather than instating it by own its own.

public class Test {public static void main(String... args) {     JAXBContext context = JAXBContext.getInstance(Event.class);    Unmarshaller unmarshaller = context.createUnmarshaller();      UserContext userContext = null; // fetch it from some where      unmarshaller.setAdapter(UserAdapter.class, new UserAdapter(userContext));      Event event = (Event) unmarshaller.unmarshal(..);   }}

setAdapter method is available on both Marshaller & Unmarshaller

Note:setAdapter on marshaller / unmarshaller does not mean that you don't have to use @XmlJavaTypeAdapter.