Using groovy classes within Gradle build
13,496
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
Author by
jonatzin
Updated on September 16, 2022Comments
-
jonatzin over 1 year
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
-
jonatzin about 10 yearsDo 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?
-
tim_yates about 10 yearsNot 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?
-
Louis about 5 yearsgradle 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.