javaanttaskdef

How to pass arguments to an Ant <taskdef> custom Java class


I wanted to pass some function arguments to the function public void execute() which is a basic entry point to a class from the Java code when we use <taskdef> in Ant. So my question is can we able to pass arguments to a function with <taskdef> in Ant if so how to pass the parameters to the function.

Providing below my sample Ant code and Java code that needs to be modified.


Code for build.xml

<?xml version="1.0" encoding="ISO-8859-1"?>
<project name="MyTask" basedir="." default="use">
    <target name="use" description="Use the Task" depends="jar">
        <taskdef name="helloworld" classname="HelloWorld" classpath="HelloWorld.jar"/>
        <helloworld/>
    </target>

    <!-- invoking java files by java task  -->
    <target name="javatask">
        <java fork="true" failonerror="yes" classname="HelloWorld.class"/>
    </target>

    <target name="jar" depends="compile">
        <jar destfile="HelloWorld.jar"
       basedir="."/>
    </target>

    <target name="compile" depends="clean">
        <javac srcdir="." destdir="." includeantruntime="false"/>
    </target>

    <target name="clean">
        <delete file="HelloWorld.jar"/>
    </target>
</project>

HelloWorld.java

    public class HelloWorld {
        public void execute() {
            System.out.println("Hello World first function");
        }
    }

I need to pass a function argument to execute() function. How can I achieve this?


Solution

  • Try this:

    public class HelloWorld extends Task {
    
    String message;
    public void setMessage(String msg) {
        message = msg;
    }
    
    public void execute() {
        if (message==null) {
            throw new BuildException("No message set.");
        }
        log(message);
    }
    

    }

    And

    <target name="use" description="Use the Task" depends="jar">
        <taskdef name="helloworld" classname="HelloWorld" classpath="HelloWorld.jar"/>
        <helloworld message="Hello World" />
    </target>
    

    See The Howto