I’m working on converting my Java object model into an XSD schema file. The challenge I’m facing is with interface handling during the XSD generation process.
My Java structure includes:
- A main interface with multiple concrete classes implementing it
- A container class that has a field referencing the interface type
When I attempt to use JAXB for schema generation, I get this error:
MyInterface is an interface, and JAXB can't handle interfaces.
this problem is related to the following location:
at MyInterface(src/MyInterface.java:1)
at DataContainer.item(src/DataContainer.java:12)
at DataContainer(src/DataContainer.java:8)
Is there a way to make JAXB understand that my DataContainer should accept either ImplementationA or ImplementationB for the interface field? I want the generated XSD to reflect this polymorphic relationship properly.
I know about using xsd:choice as a workaround, but that feels like a hack. Ideally, I’d prefer a solution where adding new implementations doesn’t require manual XSD updates.
JAXB hates interfaces since it needs concrete types for serialization. I’ve found the cleanest fix is @XmlElements with multiple @XmlElement annotations on your container field. Creates a proper choice in the XSD without feeling like a hack.
@XmlElements({
@XmlElement(name="implA", type=ImplementationA.class),
@XmlElement(name="implB", type=ImplementationB.class)
})
private MyInterface item;
Generates clean XSD with proper element choices and handles polymorphism correctly. You’ll still need to update annotations when adding new implementations, but the schema stays way more maintainable than manual XSD edits. Runtime marshalling works seamlessly and the XML is self-documenting with distinct element names.
Yeah, that’s a classic JAXB limitation, but there are a few ways around it. Try using @XmlElementRef on your container field instead of @XmlElement. You’ll need to add @XmlRootElement to each implementation, but it handles polymorphism way cleaner. Or just switch to an abstract base class instead of an interface - JAXB works much better with those and you’ll still get the polymorphic behavior you want. The XSD will generate proper inheritance with xsi:type attributes for runtime identification. If you want completely automatic discovery without manually updating annotations, check out MOXy or similar alternatives that handle polymorphism better than standard JAXB.
i feel ur pain - jaxb and interfaces don’t play nice together
. @XmlSeeAlso is ur friend here. it basically tells jaxb which impls to expect, so it won’t freak out when it hits ur interface.