Ant task to execute a main class with command line args parameters

Yeah, once again another HelloWorld stuff on the web. I was just curious to try to execute a Main class with an Ant script and found out that I couldn´t find the straight working snippets online easily, because I couldn´t get to know how to set the classpath. So I have wasted some minutes to make it work.

Let´s consider a little more than the classic HelloWorld example and pass a command line parameter as well:

package de.demo;

public class HelloWorld {

public static void main(String[] args) {
System.out.println("Hello Main! \n"  + "Parameter: "+ args[0]);


Then run following build.xml script:

<?xml version="1.0" encoding="UTF-8" standalone="no"?>

<project basedir="." default="run" name="Ant Hello World">
	<property name="src" value="." />

	<path id="classpath">
		<fileset dir="${src}">

	<target name="compile">
		<javac srcdir="." />

	<target name="run" depends="compile">
		<!-- Print directly in the console -->
		<echo message="Hello World!" />
		<!-- Run main class with parameters-->
		<java classname="de.demo.HelloWorld">
			<arg value="10"/>
			<classpath refid="classpath">


In the console you will see something like:

Buildfile: C:\Users\liparulol\workspace\AntDemos\buildHelloWorld.xml
[javac] C:\Users\liparulol\workspace\AntDemos\buildHelloWorld.xml:14: warning: 'includeantruntime' was not set, defaulting to build.sysclasspath=last; set to false for repeatable builds
[javac] Compiling 1 source file
[echo] Hello World!
1 Hello Main!
1 Parameter10
Total time: 745 milliseconds

That´s it!

Comments are closed.