Search code examples
antnestedantbuilder

Run nested task in custom task


I have written my own ANT task to perform some function. However, I need this task to invoke a java task as a nest task. So I have the following code in my build file:

<mytask ... >
  <java ... />
</mytask>

I would like to run a piece of code after the java task finishes executing but before mytask completes, for the purpose of cleanup.

Is this a broken design, not recommended in build files? If not, which method should I over-ride in order to run the cleanup method?


Solution

  • Let your task implement the org.apache.tools.ant.TaskContainer interface, write your own addTask(Task task) method.

    For example (it should only take a task named "java"):

    private List<Task> _nestedTask = new ArrayList<>();
    
    public void addTask(Task task) {
        if (task.getTaskName().equals("java")) {
            _nestedTasks.add(task);
        }
        else {
            throw new BuildException("Support only nested <java> task.");
        }
    }
    

    Please note that if you write multiple nested <java> tasks in your build file, you need to handle them by your self. To execute the nested <java> tasks, just iterate through the list and call execute() method for each task.

    Update:

    When a nested task is added, it doesn't run automatically. It won't even run if its execute() method is not called in your custom task.

    So... A very basic and simple example:

    // your custom task's execute...
    public void execute() {
        //do something
    
        for (Task task : _nestedTask) {
            task.perform(); // here the nested task is executed.
        }
    
        //do something
    }