简体   繁体   中英

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?

I think this should work for you.

<?xml version="1.0"?> 

<project name="Build-example" default="main" basedir="."> 
<taskdef name="mytask" classname="com.urdomain.HelloWorld " classpath="bin"          /> 

<target name="main"> 
<mytask message="Hello my Task!" /> 

</target> 
</project> 

Here in the above code snippet , you can define the taskdef name across the class to which u need to pass the parameters. Parameters could be passed aa above. Here I tried passing 'Hello my Task' as the message.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM