Home Tutorials Ant Executes a Java class within the Ant VM

Related Tutorials


 
 

Share on Google+Share on Google+

Executes a Java class within the Ant VM

Advertisement
This example illustrates how to call class file through build.xml file.

Executes a Java class within the Ant VM

     

This example illustrates how to call class file through build.xml file. The build.xml file is used to compile and run the java file and print the calculated value on command prompt. Here we are using only four targets, "clean" target deletes any previous "build" directory; second one is used to create "build" and "src" directories which depend on <target name="clean">, after execution of the clean target, this target will be executed; third one is used to compile the java file from "src" directory, it transforms source files in to object files in the appropriate location in the build directory and it depends on <target name="prepare">; forth one is used to run the class file and it depends on <target name="compile">. The debug keyword is used to find the error and optimize is used to find resources of source and destination directory. In the target run, fork="true" is used to display output and failonerror is used to display error report. 

 

 

<?xml version="1.0"?>
<project name="add" default="run" basedir=".">

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

  <target name="prepare" depends="clean">
  <mkdir dir="src"/>
  <mkdir dir="build"/>
  </target>

  <target name="compile" depends="prepare">
  <javac srcdir="src" destdir="build" debug="on" optimize="on"/>  
  </target>

  <target name="run" depends="compile">
  <java fork="true" failonerror="yes" classname="Addition" classpath="build">  
  <arg line=""/>
  </java>
  </target>

</project>


Simply copy and paste the following source code in the src directory and then run with ant command. The following output will be displayed:

class Addition{
  public static void main(String[] args) {
  int a=5;
  int b=10;
  int add = a + b;
  System.out.println("Addition = " + add);
  }
}



Download Source Code

     

Advertisements

If you enjoyed this post then why not add us on Google+? Add us to your Circles



Liked it!  Share this Tutorial


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: September 6, 2008

Related Tutorials

Discuss: Executes a Java class within the Ant VM  

Post your Comment


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 
Comments:0
DMCA.com