Ant

Basics of Apache Ant

While build tools like Maven and Gradle are the dominant choices for many Java developers today, I would argue that sometimes the best choice for a project is still Apache Ant.

Personally I prefer to start every new project as a Maven project myself, but applying Maven to an existing and messy project can sometimes be a nightmare; the simplicity and effectiveness of Ant just makes sense for situations like this.

This post will hopefully provide enough to make you dangerous with Apache Ant.

Thinking in Terms of Tasks

I believe the easiest way to understand the purpose of Apache Ant (or any build tool in general) is to think in the lowest level possible.

For example, consider the steps needed to build a simple “Hello World” application:

  1. Clean any existing binaries
  2. Create a directory for your class files
  3. Compile your source files (using javac) and place them in the new class directory

When creating an Ant build script, you are essentially listing these exact steps.  At its most basic form, our script would look something like this:

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!--A project is always the root node of your script-->
<project>
	<!-- A target is a container for all of your tasks (such as deleting, compiling, etc)-->
	<target name="build">
		<delete dir="./build"/>
		<mkdir dir="./build"/>
		<javac srcdir="./src" destdir="./build"/>
	</target>
</project>
Breaking out your Targets

As shown, a simple script may only require a single target.  However, for anything more complex than  “Hello World”, you will likely want to break your targets further.

You can then set target dependencies by setting a value for the target’s “depends” attribute.

When multiple targets are available, you can also specify the default target attribute of “project”.

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<project default="build">
	<target name="clean">
		<delete dir="./build" />
	</target>
	
	<target name="init" depends="clean">
		<mkdir dir="./build" />
	</target>

	<target name="build" depends="init">
		<javac srcdir="./src" destdir="./build" />
	</target>
</project>

The script above specifies “build” as the default target.  It also specifies that “clean” must be executed before “init” (through its “depends” attribute) and that “init” must be executed before “build”.

As can be seen, Ant is incredibly simple, and yet immensely powerful.  Although rarely used for new projects nowadays, I highly recommend new developers learn it as another tool for your toolbox.  Happy building.