Java Reference
In-Depth Information
Customizing Code Generation in JAXB
Problem
You want to gain advanced capabilities for how JAXB generates your Java code during un-
marshaling. For example, you'd like JAXB to add a hashcode and an equals method to your
generated class, or maybe a toString method.
Solution
Check out the JAXB plug-ins available at https://jaxb2-commons.dev.java.net , or write your
own.
At the time of this writing, the JAXB 2 commons project features 16 plug-ins and utilities
that extend the capabilities of JAXB. Those hosted at the jaxb2-commonssite allow you to do
some of the useful things that you might normally do if you were writing your own objects
instead of generating them. For example, there is a plug-in to generate identifiers using camel
case and one to create property listeners around fields.
The plug-ins are easy to use. Simply download the JAR from the website and add it to XJC's
classpath along with the necessary plug-in option. Here is an example invocation for using the
property listener injector plug-in:
> xjc -cp property-listener-injector.jar -Xinject-listener-code Book.xsd
If you don't see a plug-in listed that has the functionality you want, you can try writing
your own. To do this, first check out the JAXB reference implementation source code to
build against. Then extend com.sun.tools.xjc.Plug-in to write your plug-in class, which
defines a series of methods that your plug-in needs to implement in order to interact with XJC.
Next, you need to package your class into a JAR and indicate its existence to the runtime using
Service Provider Interface (SPI), which was introduced internally in Java 1.4 but made pub-
licly available in Java 6. Create a text file in the META-INF/servicesdirectory of your JAR
called com.sun.tools.xjc.Plugin. In this file, type the name of your class that implements the
plug-in interface. It will be picked up at runtime as an implementor.
Then you need to add an annotation or external binding to indicate that your schema should
use this customization. For information on how to do this, see Customizing How a Java Class
Is Generated from Schema .
Search WWH ::




Custom Search