简体   繁体   English

JAXB XML适配器未与XmlElements批注类型一起使用

[英]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. 我有一个类A,带有子类B和C。此外,我在package-info.java文件中使用XmlJavaTypeAdapters批注。 In it I am specifying adapters for B and C 我在其中指定B和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: 在要用JAXB序列化的包xyz中的类中,我正在编写以下代码:

@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. 通常,这种结构在不需要XML适配器时始终可以使用。 However, now, it seems to be that JAXB is not using the defined XML adapters for the @XmlElement types. 但是,现在看来,JAXB并未针对@XmlElement类型使用定义的XML适配器。 It is trying to serialize "b-entry" and "c-entry" without the adapters, which fails. 它试图在没有适配器的情况下序列化“ b-entry”和“ c-entry”。
I have many other XmlAdapters on package level, they all work unless you use them with @XmlElements. 我在程序包级别上还有许多其他XmlAdapter,它们都可以工作,除非您将它们与@XmlElements一起使用。

Is this a bug or a shortcoming of JAXB? 这是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. 原来,确实不可能将@XmlElements与包级XML适配器或任何XML适配器一起使用。

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> . 我通过创建List<B>List<C>解决该问题,然后在代码中将它们组合在一起以形成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 . 但是,对于XML适配器使用列表元素而言,最重要的是:不允许指定@XmlElementtype属性。 Leave it out and the XML adapter will work. 保留它,XML适配器将起作用。 This means, the type argument of the List has to be the exact type for which you have the adapter. 这意味着,列表的类型参数必须是您拥有适配器的确切类型。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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