Last Updated: February 25, 2016
·
3.249K
· tomaslongo

Compile Groovy Before Java in Gradle Build

The groovy plugin extends the java plugin in order to compile groovy alongside java. The default compile behaviour is to compile java before groovy, which lets you use java objects inside groovy code.
This leads to problems when you want to do things the other way round: Using groovy objects inside java. The result is the compiler complaining that it can not find any groovy stuff.

The simple solution is to let groovy compile everything in which case the compilation order is
groovy before java. Just add this snippet to your gradle.build file

sourceSets {
  main {
    groovy {
      // this makes the groovy-compiler compile groovy- as well 
      // as java-files.
      // Needed, because java is normally compiled before groovy.
      // Since we are using groovy objects from java, we need it
      // the other way round.
      srcDirs = ['src/main/groovy', 'src/main/java']
    }
    java {
      srcDirs = [] // don't compile Java code twice
    }
  }
 }

Credits to Peter Niederwieser who posted this snippet at StackOverflow