What can you do in the ant Task.init () method?

I am developing several custom ant tasks that should all initialize the same objects. I wanted to initialize this object in a generic superclass that extends from Task, in the init () method. But I can see from the ant task life cycle that init () is called before the child elements and attributes of the tasks are set. Therefore, all the data I need to initialize these objects is not available during init (), if I read correctly.

So why is init () called at this point? What do you even know you can use in init ()? What can it be used for?

(And is there any other method I can rely on to be called before execute (), but after my data is available?)

+5
source share
4 answers

The best guide for this is to look at the source code of the tasks Ant comes with. There seem to be 3 main use cases for init():

  • Initialization of delegate objects. For example, a task Syncdelegates most of its work to a base object, passing this element to a delegate setXYZ(). The specificity and preconfiguration of this delegate must occur before any properties are set in the task.
  • , . , SSH knownHosts , System. , Project init(), .
  • . , JUnit Junit . , .

, init() Ant.

, , , execute(). execute().

+3

init() , , . , Project.

+2

singleton, ant singleton ? .

0

execute, execute() , , . :

public abstract class BaseClass extends Task {
  public final void execute() {
    Foo foo = createFoo();
    Bar bar = createBar(foo);
    execute(foo,bar);
  }
  public abstract void execute(Foo foo, Bar bar);
}

public class BazTask extends BaseClass {
  public void execute(Foo foo, Bar bar) {
    System.out.println("foo is " + foo + " and bar is " + bar);
  }
}

You can also save created objects as fields and give the method a different name (for example executeTask) instead of overloading based on parameters.

0
source

All Articles