JavaExec task is always executing

I have the following task

task antlr4(type: JavaExec) {
    main = "org.antlr.v4.Tool"
    args = project.getAntlrArgs()
    classpath =
configurations.compile
}
  classes {
    it.dependsOn([antlr4])
}

The antlr4 task has to execute before compiling java because ANTLR4 generates a few java files.

The problem is that it executes every time any task executes (For example when running the clean task), I want it to execute only before compiling java files.

What am I doing wrong? How can I fix it ?

I’m a bit surprised that it’'s always executed. I can’t seen an misconfiguration. One note. to ensure that the task is executed before your compileJava task you should use

compileJava.dependsOn antlr4

cheers, René

I have tried using

compileJava.dependsOn antlr4

I still get the same wrong behaviour. Do you want me to post the debug log ?

It seems that the logic of your antlr4 task is accidently executed during the configuration phase. But from the task snippet you posted I can think of why this is the case.

Here let me include the full logic of the antlr4 task

/*
* Antlr Related
*/
  def findFilesOfType(dir,endsWith){
    def collection = []
    dir.eachFileRecurse(groovy.io.FileType.FILES) {
        if(it.name.endsWith(endsWith)){
            collection.add(it.absolutePath)
        }
    }
    return collection
}
def getAntlrArgs(){
    def listener = true
    def visitor = true
    def arg = []
      if(project.hasProperty("listener")){
        listener = project.listener
    }
    if(project.hasProperty("visitor")){
        visitor = project.visitor
    }
    if(listener) {
        arg.add("-listener")
    }else {
        arg.add("-no-listener")
    }
    if(visitor) {
        arg.add("-visitor")
    }else{
        arg.add("-no-visitor")
    }
    def g4s = project.findFilesOfType(file('src'),".g4")
    arg += g4s
    println "Antlr args" + arg
    return arg
}
  task antlr4(type: JavaExec) {
    main = "org.antlr.v4.Tool"
    args = project.getAntlrArgs()
    classpath =
configurations.compile
}
  compileJava.dependsOn antlr4

are you sure the task is really executed and not just configured. With the snippet above, you’ll always get the logging message “antlr args…” as this is done in the configuration of the task. But I guess “org.antlr.v4.Tool” is only executed when the task is really triggered.

Sorry for posting this as a reply but I was unable to comment. Thanks a lot, I just checked, It wasn’t really executing, It was just printing the line during the configuration phase.