简体   繁体   中英

How to handle various concrete implementations of an Interface with JAX-B

I have a class that any I need to marshal to XML.

@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class ClassToBeMarshalled {
    public Interface object;
}

The Interface is implemented by a lot of concrete classes and most of them are vendor specific whose source code I don't have access to.

So my problem is:

If I try to marshal that class, JAX-B will complain that the current concrete implementation of Interface is not known in the context - In another words, the concrete class was not loaded into the context by calling JAXBContext.newInstance providing the current implementation.

The most common ways to sort out that problem are:

1) Use XMLSeeAlso - not a viable option as there are a lot of concrete classes

2) Annotate each class with @XmlRootElement - not a viable option as I don't have access to all the classes

Does anyone know a way to make JAX-B load the concrete class into its context as the need arises?

Thanks.

PS: I'm using JAX-B RI

You could mark your object as @XmlAnyElement (InterfaceHandler.class) where InterfaceHandler is a DomHandler capable of translating between a DOM representation and the actual implementing classes. That handler should probably store the class name when marshalling, and use that class name to create the instance when unmarshalling. It might either configure the instance manually, perhaps using some helper classes designed to work with beans, or it might use another jaxb context which includes that specifically named class and will handle that object with all its nested children.

Also have a look at the @XmlElementRef annotation. I fear that in order to make this work properly, you'd have to at least know all the implementing classes at compile time, but perhaps there is a way you can make this work for you as well, with less trouble than the generic solution outlined in the previous paragraph.

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