8

I'm trying to run a Groovy class from within my build.gradle file. I'm following the direction in the use guide however I get an error.

The build file is:

apply plugin: 'java'
apply plugin: 'groovy'

  main {
    java {
      srcDirs = ["$projectDir/src/java"]
    }
    groovy {
      srcDirs = ["$projectDir/src/groovy"]
    }
  }

    dependencies {
        compile 'org.codehaus.groovy:groovy-all:2.2.0', files(....)
    }

    task fooTask << {
        groovyClass groovyClass = new groovyClass()
        groovyClass.foo()
    }

The groovy class is very simple:

    public class groovyClass {

            public void foo() {
                    println 'foo'
            }
    }

However when I try to run gradlew compile fooTask I get the following error:

unable to resolve class groovyClass

Any idea why?

Thanks

tim_yates
  • 167,322
  • 27
  • 342
  • 338
jonatzin
  • 922
  • 1
  • 13
  • 30
  • I already tried the solution suggested in [this post](http://stackoverflow.com/questions/11580057/using-class-from-groovy-file-located-in-another-folder-gradle) but the issue still persists – jonatzin Feb 20 '14 at 10:57

1 Answers1

25

You need to add the class to buildSrc if you want to reference it from the build (and not in a simple Exec task). Given this directory structure:

|-buildSrc
|    |- src
|        |- main
|            |- groovy
|                |- GroovyClass.groovy
|- build.gradle

Where GroovyClass.groovy is:

class GroovyClass {
    void foo() {
        println 'foo'
    }
}

And build.gradle is:

apply plugin: 'groovy'

dependencies {
    compile 'org.codehaus.groovy:groovy-all:2.2.1'
}

task fooTask << {
    GroovyClass g = new GroovyClass()
    g.foo()
}

Then, running gradle fooTask gives the output:

$ gradle fooTask
:buildSrc:compileJava UP-TO-DATE
:buildSrc:compileGroovy UP-TO-DATE
:buildSrc:processResources UP-TO-DATE
:buildSrc:classes UP-TO-DATE
:buildSrc:jar UP-TO-DATE
:buildSrc:assemble UP-TO-DATE
:buildSrc:compileTestJava UP-TO-DATE
:buildSrc:compileTestGroovy UP-TO-DATE
:buildSrc:processTestResources UP-TO-DATE
:buildSrc:testClasses UP-TO-DATE
:buildSrc:test UP-TO-DATE
:buildSrc:check UP-TO-DATE
:buildSrc:build UP-TO-DATE
:fooTask
foo

BUILD SUCCESSFUL

Total time: 4.604 secs
tim_yates
  • 167,322
  • 27
  • 342
  • 338
  • 2
    Do you know if there is a way to change where gradle looks for the classes, so instead of buildSrc/src/main/groovy it will look for it at src/main/groovy? – jonatzin Feb 20 '14 at 12:56
  • Not that I know of. To run the build it will have first had to run the build, so you get a chicken and egg situation. Not sure if a symbolic link in buildSrc to the groovy file in SRC will work if the file is required in both and you don't want to maintain two files? – tim_yates Feb 20 '14 at 14:14
  • gradle will fetch your groovy sources in `srcDirs` from your build.gradle. Put whatever path you would like to be a gradle source directory and you're good to go. – Louis Apr 11 '19 at 07:46