Create Gradle Plugin ( @TaskAction)

when make custom Gradle plugin and my task
i`m going to extends DefaultTask

then I’m wondering TaskAction Annotation

DefaultTask just extends AbstractTask

abstractTask contained execute method

public void execute(Task task) {
        ClassLoader original = Thread.currentThread().getContextClassLoader();
        Thread.currentThread().setContextClassLoader(this.action.getClass().getClassLoader());

        try {
            this.action.execute(task);
        } finally {
            Thread.currentThread().setContextClassLoader(original);
        }

    }

how can detect TaskAction annotation when calling execute method?

We have an annotation processor (AnnotationProcessingTaskFactory) that creates actions for methods annotated with @TaskAction.

You don’t have to do anything other than define a class that extends DefaultTask and annotate one method with @TaskAction. That becomes the action for that task.

@sterling after all this years your answer still shed some light on @TaskAction annotation processing.

Now I understand that the method annotated with @TaskAction will be processed by the AnnotationProcessingTaskFactory. Lets say there are two methods in the concrete DefaultTask implementation annotated with @TaskAction. I know this doesn’t make much sense. One could just use one annotated @TaskAction method and then call other methods form it, but it still viable DefaultTask definition.

Is there any order by which they will be executed? By order in which they are defined? Will it be unpredictable?

for example

abstract class FilesTask extends DefaultTask {

  @TaskAction
  def sort() {
    ...
  }

  @TaskAction
  def generateReport() {
    ...
  }
}

From a quick look at the sources and my memory, I’d say

  • if you have multiple incremental actions (no matter whether old or new api) you get an error
  • if you have one or none incremental action and potentially further non-incremental actions, the inremental one is executed first if present and the non-incremental ones last, where the order of the non-incremental ones is defined by the order they are returned from getDeclaredMethods() and thus JVM dependent and not defined afair.
1 Like