How to write an Ant xml build file to Generate JAXB Code and Compile and Build it to a Jar


There is a pretty common situation to use a java classes generator and to create classes based on a defined pattern. Hibernate, Castor, Jaxb are a few examples. I prefer to have those classes packed in a separate jar file. Since they are generated files it's not a good practice to modify them, so there is not need to have them in your project. Debugging is the case when you need the source of generated classes. In this case you can simply attach the jar containing sources in your IDE (eclipse supports it, I think other IDE support it either).

Mainly you have to use 2 ant tasks after the java code is generated, one for compiling the classes, the other one to package them. In the following example I'm using ant to generate some jaxb classes, then to compile them and build a jar file. In this task there are 2 ant tasks, named compile and jar, responsible for compiling and generating the ant file:

<?xml version="1.0"?>
<project name="bbindings.jaxb" default="jar" basedir=".">

<property name="home" value="."/>
<property name="build" value="build"/>
<property name="logs" value="logs"/>
<property name="src" value="src"/>
<property file=""/> 

<target name="clean">
    <delete dir="${logs}"/>
    <delete dir="${build}"/>
    <delete dir="${src}"/>

<target name="init" depends="clean">
    <mkdir dir="${build}"/>
    <mkdir dir="${logs}"/>
    <mkdir dir="${src}"/>

<target name="copy_xsd" depends="init">
    <copy file="${env.XSD_FILE}" todir="${src}"/>

<target name="generate_jaxb" depends="copy_xsd">
    <java jar="${env.JWSDP_HOME_LIB}\jaxb-xjc.jar" fork="true" dir="${src}">
        <arg value="-p"/>
        <arg value="com.bbindings.jaxb"/>
        <arg value="${home}/${env.XSD_FILE}"/>

<target name="compile" depends="init,generate_jaxb">
    <!-- Compile the java code -->
    <javac srcdir="${src}" destdir="${build}">
            <pathelement location="${env.JWSDP_HOME_LIB}/jaxb-api.jar"/>
            <pathelement location="${env.JWSDP_HOME_LIB}/jaxb-impl.jar"/>
            <pathelement location="${env.JWSDP_HOME_LIB}/jaxb-xjc.jar"/>
            <pathelement location="${env.JWSDP_HOME_LIB}/jsr173_api.jar"/>
<target name="jar" depends="compile">
    <!-- Build the jar file -->
    <jar basedir="${build}" destfile="${build}/${env.JAR_FILE}"/>