O'Reilly logo

Java Extreme Programming Cookbook by Brian M. Coyner, Eric M. Burke

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Passing Arguments to a Buildfile

Problem

You want to pass system properties to a buildfile. Java system properties are a more portable alternative to environment variables.

Solution

Pass the system properties to Ant using the -D command-line argument. For example:

ant -Dprop1="My Property" run

Within the buildfile, refer to the property using Ant’s ${prop1} syntax. You can specify default values for properties using the <property> tag, and you can pass system properties to Java applications using the <sysproperty> tag nested within the <java> element.

Discussion

Example 3-3 shows an Ant buildfile that demonstrates system properties. It echoes the property name/value pairs to the console, and then invokes a Java application that echoes the same properties.

Example 3-3. Buildfile demonstrating system properties

<?xml version="1.0"?>
<project name="sysprops" default="run" basedir=".">
  <!-- define two properties -->
  <property name="prop1" value="Property 1 from Buildfile"/>
  <property name="prop2" value="Property 2 from Buildfile"/>

  <target name="clean">
    <delete dir="com"/>
  </target>

  <target name="compile">
    <javac srcdir="." destdir=".">
      <classpath path="."/>
    </javac>
  </target>

  <target name="run" depends="compile">
    <!-- echo each of the properties to the console -->
    <echo message="Now in buildfile..."/>
    <echo message="prop1     = ${prop1}"/>
    <echo message="prop2     = ${prop2}"/>
    <!-- The 'prop3' property must be defined on the command 
         line or it shows up like '${prop3}' -->
    <echo message="prop3 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required