Skip to main content

JAXB and interfaces

Posted by kohsuke on June 6, 2006 at 10:00 PM PDT

Today's question from our users is "why doesn't JAXB handle interfaces?"

First, it's not quite accurate to say "we don't support interfaces". It's just that you need put some annotations to make it work, and it's more restrictive than we'd like it to be. Fore more about how to map interfaces, see the unofficial JAXB guide that I'm compiling.

But what I'd like to talk about today is why JAXB can't handle interfaces like it does classes, and there's a good technical reason for it.

Suppose if you have interfaces annotated just like you'd classes:

@XmlType(name="foo")
interface Foo {
  @XmlElement
  String getName();
  void setName(String);
}

@XmlType(name="bar")
interface Bar {
  @XmlElement
  String getAddress();
  void setAddress(String);
}

OK, so far no big deal, we can map them to two complex types. But now, how do you do this?

interface Zot extends Foo, Bar {
}

class FooImpl extends BaseClass implements Foo {
  String getAddress() { ... }
}

It's really not possible to map Zot nor FooImpl to XML Schema concepts --- I mean, you can't do multiple inheritance in XML Schema. Even if you forget the idea of generating a schema, you still can't even bind them to XML, since we can't decide whether address should come before name or vice versa.

Another serious problem is that when you annotated interfaces, your expectation is that JAXB will be able to bind any classes provided that it implements the said interface, but if you think about it, it just doesn't work that easily. For example, how does the unmarshaller create an instance, if it only knows about an interface? Or if you try to marshal an instance of a class that both implements Foo and Bar, how does the JAXB runtime figure out whether it should be marshalled as Foo or marshalled as Bar?
I hope you get some idea of why interfaces and classes are so different.

Now, that said, handling of interfaces in JAXB turns out to be really painful for many people. So I think some improvements would be really nice --- it's just that I'm not too sure how.

Related Topics >>