Java Reference
In-Depth Information
If you're committed to Ant builds using XML, that's all there is to it. If, however, you're
willing to switch your build language to Groovy, there are a couple of other alternatives.
The next two subsections use Groovy for the build language but are still fundamentally
based on Ant.
5.3.3. Writing your build in Groovy with AntBuilder
The standard Groovy library includes a class called
groovy.util.AntBuilder
. To
use it you need to add the Java-based Ant JAR library files to your classpath, but once you
do,
AntBuilder
lets you replace the XML syntax with Groovy.
Any task defined by Ant can be used through the
AntBuilder
class. For example, the
following listing shows a simple script that makes a copy of its own source, verifies that it
worked, and then deletes the copy.
Listing 5.5.
antbuilder.groovy
, which copies itself
def
ant =
new
AntBuilder()
String dir = 'src/main/groovy'
assert
!(
new
File("$dir/
antbuildercopy.groovy
").exists())
ant.
echo
'about to copy the source code'
ant.
copy
file:"$dir/
antbuilder.groovy
",
tofile:"$dir/
antbuildercopy.groovy
"
assert
(
new
File("$dir/
antbuildercopy.groovy
").exists())
ant.
echo
'deleting the copied file'
ant.
delete
file:"$dir/
antbuildercopy.groovy
"
Builder code and regular Groovy code are freely intermixed in this example. The Ant tasks
used here are
echo
,
copy
, and
delete
, but it would be easy enough to use others like
javac
,
junitreport
, or even optional Ant tasks like
mail
. As long as the required
Ant libraries are in the classpath, each will work.
There's actually a simplification available. The
with
syntax is available as a part of
Groovy's metaprogramming capabilities. It can simplify the previous listing down to that
shown in the next listing.