Creating task that runs the build task with compiler flags


(Alex) #1

I have a Java project in which I would like to create a task that runs the build task with some annotation processors enabled through compiler flags. My impression from Googling is that implementing this by running something akin to "add compiler flags, then invoke build" is not possible, as a task cannot pass control to another task. I wrote this instead:

task buildWithProcessors {
    compileJava.options.compilerArgs += [<flags>]
}
compileJava.dependsOn buildWithProcessors

Not really what I intended, unfortunately, but at least it passes the options, albeit for every invocation of gradle build.

I considered using a command line flag to indicate whether the extra compiler flags are desired, but I felt it wasn’t ideal due to the fact that it wouldn’t show up in gradle tasks. There was also the option of using an empty withProcessors task along with gradle.taskGraph.whenReady, but, again, I thought that it wasn’t really ideal to require the user to type gradle build withProcessors instead of gradle buildWithProcessors

I saw that Maven has a way to specify annotation processors without messing with compiler flags, but I didn’t see an equivalent for Gradle.

Is there a better/more Groovy-/Gradle-style way of doing something like this? Am I missing another way of looking at the problem that doesn’t require such a setup?


(Mark Vieira) #2

Why not use gradle.taskGraph.whenReady and just have the buildWithProcessors task depend on build?


(Alex) #3

I thought doing that wouldn’t work, as the annotation processors are run by passing flags to javac, and if javac has already run the processors can’t really do anything.


(Mark Vieira) #4

The configuration contained in gradle.taskGraph.whenReady (which in this case would be the optional javac arguments) will run before any tasks are executed. Effectively what we are saying is “apply this configuration to my build, but only when I run this particular task”.

gradle.taskGraph.whenReady { graph ->
  if (graph.hasTask(':buildWithProcessors') {
    compileJava.options.compilerArgs += [<flags>]
  }
}

task buildWithProcessors {
  dependsOn build
}

(Alex) #5

Ah, now that makes sense. Thank you for clearing up that misconception!