简体   繁体   中英

JAXB XML adapters not used with type of XmlElements annotation

I have a class A, with subclasses B and C. Furthermore I am using the XmlJavaTypeAdapters annotation in the package-info.java file. In it I am specifying adapters for B and C

@XmlJavaTypeAdapters({
    @XmlJavaTypeAdapter(value = BAdapter.class, type = B.class),
    @XmlJavaTypeAdapter(value = CAdapter.class, type = C.class)
})
package xyz;

In a class in package xyz that is to be serialized with JAXB I am writing this:

@XmlElementWrapper(name = "entries")
@XmlElements({ @XmlElement(name = "b-entry", type = B.class),
               @XmlElement(name = "c-entry", type = C.class) })
private List<A> entries = new ArrayList<>();

This construct in general always works when not requiring XML adapters. However, now, it seems to be that JAXB is not using the defined XML adapters for the @XmlElement types. It is trying to serialize "b-entry" and "c-entry" without the adapters, which fails.
I have many other XmlAdapters on package level, they all work unless you use them with @XmlElements.

Is this a bug or a shortcoming of JAXB? Is my approach wrong?
Please note that I have to use the package level annotation, I cannot annotate directly in the class.

Turns out, it is indeed impossible to use @XmlElements together with package level XML adapters or possibly any XML adapter.

I worked around the issue by creating a List<B> as well as a List<C> and then later in code combining them to form a List<A> .

What is most important however for XML adapters to work with list elements: You are not allowed to specify the type attribute of @XmlElement . Leave it out and the XML adapter will work. This means, the type argument of the List has to be the exact type for which you have the adapter.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM