JAXB override @XmlElement type of list

自闭症网瘾萝莉.ら 提交于 2019-12-06 05:48:15

There is no way to change (e.g. override) the @XmlElement annotation of a super class. At least not using annotations.

  • It doesn't matter what @XmlAccessorType you use (e.g. FIELD, PROPERTY, PUBLIC, NONE).
  • It doesn't make any difference if you put the annotations on the fields or on the getters.

However, there is a reasonable alternative. The MOXy implementation of JAXB offers the ability to define the metadata/bindings in an xml file. In fact every java annotation has an XML alternative. But it gets better: You can combine both java annotations AND these xml metadata. The cool thing, is that MOXy will merge both declarations, and in case of conflict, the XML defined metadata gets a higher priority.

Assuming that the Bean1 class is annotated as above. Then it's possible to redefine the binding, in an xml file. e.g.:

<xml-bindings xml-accessor-type="PROPERTY">
  <java-types>
    <java-type name="Bean1">
      <xml-element java-attribute="childList" name="child" 
                   type="BeanChild2" container-type="java.util.ArrayList" />
    </java-type>
  </java-types>
</xml-bindings>

This new bindings file is needed during the creation of the context object.

// use a map to reference the xml file
Map<String, Object> propertyMap = new HashMap<>();
propertyMap.put(JAXBContextProperties.OXM_METADATA_SOURCE, "bindings.xml");

// pass this properyMap during the creation of the JAXB context.
JAXBContext context = JAXBContext.newInstance(..., propertyMap);

MOXy will merge the java annotations and the XML bindings, and in case of a conflict the XML defined settings are applied. In this case, the earlier @XmlElement(name=child) annotation is replaced by an xml definition which is equivalent to @XmlElement(name=child, type=BeanChild2.class).

You can read more about the XML bindings here.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!