Skip to main content

Binding 3rd party classes witih JAXB

Posted by kohsuke on July 12, 2007 at 8:47 AM PDT

One common complaint from the JAXB users is the lack of support for binding 3rd party classes. The scenario is this — you are trying to annotate your classes with JAXB annotations to make it XML bindable, but some of the classes are coming from libraries and JDK, and thus you cannot put necessary JAXB annotations on it.

Knowing that this would be a problem, I designed the JAXB RI with a necessary hook to fix this problem. It enables programatic introduction of annotations to the JAXB runtime, so it allows people to define annotations in XML (or any other format), and make JAXB see those as if those were in the class files.

I've been asking various folks to actually implement such extension, and today I'm very happy to see that JBoss finally pulled this off with their JAXBIntroduction project.

With this project, you can write annotations in XML like this:

<br /><jaxb-intros xmlns=""><br />  <Class name="com.activebpel.ordermanagement.CustomerOrder"><br />    <XmlType propOrder="orderDate,name,address,items" /><br />    <Field name="orderDate"><br />      <XmlAttribute name="date" required="true" /><br />    </Field><br />    <Method name="getXYZ"><br />      <XmlElement namespace="http://org.jboss.esb/quickstarts/bpel/ABI_OrderManager"<br />                  nillable="true" /><br />    </Method><br />  </Class><br /><br />  <Class name="com.activebpel.ordermanagement.*"><br />    <Method name="get.*"><br />      <XmlElement namespace="" /><br />    </Method><br />  </Class><br /></jaxb-intros><br />

As you see, the structure mirrors a Java class. It's also got the wildcard support, too.

You can then create JAXBContext like this:

JaxbIntros config = IntroductionsConfigParser.parseConfig(getClass().getResourceAsStream("annotations.xml"));
IntroductionsAnnotationReader reader = new IntroductionsAnnotationReader(config);

JAXBContext jaxbContext = JAXBContext.newInstance(
    new Class[] {CustomerOrder.class},

It doesn't support all the JAXB annotations yet, but I'm sure they'd be happy to expand the support. Also note that this extension can be used to bind the same set of classes to multiple XML representations, so this could be used for dealing with a versioning problem.

Related Topics >>