This article introduces the use of the Ant Java API, and shows how to call tasks from an existing build file, how to set-up properties used in the project, and how to add new targets and tasks to the project.
First you have to download the Ant API. So go the the Ant website and download the binary distribution. Extract the jar files to your lib directory, and add them to your classpath.
Import the following packages :
Then, the following code loads an existing file into an Ant project.
The following snippet shows how to call ant targets.
You simply call a target by giving its name to the executeTarget method.
Ant targets can use properties defined in the build file or in external properties file.
You can dynamically set properties with the following code.
You can also dynamically create a new ant target, add it to the project.
Now you know how to use ant from java. I'll talk about writing your how tasks in a future post.
First you have to download the Ant API. So go the the Ant website and download the binary distribution. Extract the jar files to your lib directory, and add them to your classpath.
Loading the project
Import the following packages :
import org.apache.tools.ant.*; import org.apache.tools.ant.taskdefs.*;
Then, the following code loads an existing file into an Ant project.
File buildFile = new File("build.xml");
Project antProject = new Project();
// setting up the ${ant.file} property
antProject.setUserProperty("ant.file",
buildFile.getAbsolutePath());
antProject.init();
// parsing the file
ProjectHelper helper = ProjectHelper.getProjectHelper();
helper.parse(antProject, buildFile);
Calling targets
The following snippet shows how to call ant targets.
You simply call a target by giving its name to the executeTarget method.
String targetName = "build"; antProject.executeTarget(targetName); String defaultTarget = antProject.getDefaultTarget(); antProject.executeTarget(defaultTarget);
Ant targets can use properties defined in the build file or in external properties file.
${myMessage}
You can dynamically set properties with the following code.
antProject.setNewProperty("myMessage", "Hello World");
You can also dynamically create a new ant target, add it to the project.
Target t = new Target();
Echo echo = new Echo();
echo.setProject(antProject);
echo.setOwningTarget(t);
echo.setMessage("Hello from Java");
t.addTask(echo);
antProject.addTarget("HelloJava", t);
antProject.executeTarget("HelloJava");
Now you know how to use ant from java. I'll talk about writing your how tasks in a future post.
1 comments :
Very informative!
I just found one thing to change:
ProjectHelper helper = ProjectHelper.getProjectHelper();
project.addReference("ant.projectHelper", helper);
needs to be called to support imports.
Post a Comment