Apache Ant/Property

Ant does not have variables like in most standard programming languages. Ant has a structure called properties. Understanding how properties work is critical to understanding how (and why) Ant works so well.

Here is a simple demonstration of how to set and use properties

Note that to use a property you have to put a dollar sign and left curly brace before it and a right curly brace after it. Don't get these confused with parens.

When you run this you should get the following:

Buildfile: C:\AntClass\PropertiesLab\build.xml MyTarget: [echo] Source directory is = src [echo] Build directory is build BUILD SUCCESSFUL Total time: 204 milliseconds

Ant properties are immutable meaning that once they are set they cannot be changed within a build process! This may seem somewhat odd at first, but it is one of the core reasons that once targets are written they tend to run consistently without side effects. This is because targets only run if they have to and you cannot predict the order a target will run.

Properties do not have to be used only inside a target. They can be set anywhere in a build file (or an external property file) and referenced anywhere in a build file after they are set.

Here is a small Ant project that demonstrates the immutability of a property:

When you run this, you should get the following output:

Buildfile: C:\AntClass\PropertiesLab\build.xml MyTarget: [echo] MyProperty = One [echo] MyProperty = One BUILD SUCCESSFUL Total time: 343 milliseconds

Note that despite trying to change MyProperty to be "Two", the value of MyProperty does not change. Ant will not warn you of this.

For newcomers this might seem strange, but this is ideally suited for building up complex trees of values that are set once and used over and over again. It makes your build scripts easy to maintain and reliable.

Ant also has a nice set of "built in" properties that you can use:

This demonstrates how to read system properties

When you run this program you should get an output similar to the following:

Buildfile: C:\eclipse\workspace\Ant Examples\build.xml Display-Builtins: [echo] C:\AntClass\PropertiesLab [echo] C:\AntClass\PropertiesLab\build.xml [echo] Apache Ant version 1.6.2 compiled on July 16, 2004 [echo] MyProject [echo] 1.5 BUILD SUCCESSFUL Total time: 188 milliseconds

See the ant reference manual for a full list of built-in ant and Java properties or you can try the following link for the Java properties: getProperties

Next Chapter, Next Cookbook Chapter