简体   繁体   中英

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM