简体   繁体   中英

Factory methods in JAXB accessing the element?

I am trying to use a factory method instead of a no-args constructor for JAXB.

I have multiple classes that inherit from a base class, and the only indication as to which would be instantiated is an attribute type in the xml element.

<tag-name type="boolean"/>

would instantiate a BooleanType, whereas

<tag-name type="integer"/>

would instantiate an IntegerType.

Is there any way I can access the element name / attribute values of the element being unmarshalled from within the factory method?

(Is this, perhaps, a benefit of using a factory method over a no-args constructor? Are there others?)

(I am not using MOXy)

I have multiple classes that inherit from a base class, and the only indication as to which would be instantiated is an attribute type in the xml element.

Using any JAXB (JSR-222) implementation you could use an XmlAdapter to map an inheritance relationship where an arbitrary XML attribute is the inheritance indicator.

However instead of using an arbitrary XML attribute I would use the xsi:type attribute so that the contents could be properly validated by an XML schema.

If you still wanted to use an arbitrary XML attribute and you were using EclipseLink MOXy are your JAXB provider then you could leverage the @XmlDescriminatorNode / @XmlDescriminatorValue extension:


Is there any way I can access the element name / attribute values of the element being unmarshalled from within the factory method?

JAXB implementations do allow you to specify factory classes and methods via the @XmlType annotation, but I do not believe this is what you are looking for in this use case.

To leverage the XML contents to determine the appropriate subclass to instantiate you would need to use the XmlAdapter approach.

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