u123
u123

Reputation: 16267

Using class from .groovy file located in another folder (Gradle)

I have this build.gradle file which works fine:

class Utils  {
  def doit(){
    println "hi from utils"
  }
}

task hello << {
  def utils = new Utils()
  utils.doit();
}

If I move the class/.groovy file to a sub-folder like this:

test
 -> groovy
     -> Utils.groovy
 -> build.gradle

and modify the build.gradle file to this:

dependencies {
    runtime fileTree(dir: 'groovy', include: '*.groovy')
}

task hello << {
  def utils = new Utils()
  utils.doit();
}

The Utils class can no longer be found:

...unable to resolve class Utils

I assume that the subfolder groovy should be added as an import/entry on the classpath/dependency in the .gradle file. I have read these pages:

http://gradle.org/docs/current/userguide/dependency_management.html http://gradle.org/docs/current/userguide/custom_plugins.html http://gradle.org/docs/current/userguide/custom_tasks.html

but have not been able to find any docs that describes how to import .groovy files in the .gradle file. What page am I missing that describes this simple functionality?

Upvotes: 2

Views: 6614

Answers (1)

tim_yates
tim_yates

Reputation: 171054

If you change your build.gradle to simply be

task hello << {
  def utils = new Utils()
  utils.doit();
}

Then instead of

test
 -> groovy
     -> Utils.groovy
 -> build.gradle

move the Utils.groovy file to buildSrc/src/main/groovy like so:

test
 -> buildSrc
     -> src
         -> main
             -> groovy
                 -> Utils.groovy
 -> build.gradle

and gradle should pick it up automatically.

See the section "41.4. Build sources in the buildSrc project" in the documentation for further information.

Upvotes: 5

Related Questions