简体   繁体   中英

How to access extra properties defined in build.gradle in a Groovy class?

I am defining an extra property in build.gradle:

ext {
 GRGIT_TARGET_REPO = ...
}

I have a groovy class under buildSrc/src/main/groovy

class Utils {
   def test() {
      println GRGIT_TARGET_REPO
   }
}

I have another gradle file which can access GRGIT_TARGET_REPO just fine. But if it calls the function in the class:

Utils utils = new Utils()
utils.test()

On calling the above function, I get the following error:

No such property: GRGIT_TARGET_REPO for class: Utils

Is there a way to access project/extra properties in Groovy classes?

I believe you would need to send the gradle project object into your Utils class to accomplish what you want. In other words:

class Utils {
   def project

   def test() {
      println(project.ext.GRGIT_TARGET_REPO)
   }
}

and

def utils = new Utils(project: project)
utils.test()

in your build.gradle file.

Every gradle build file has a project instance as its delegate which means that you can call all methods in the project class directly from the build file code. The example here is that the above project access calls the getProject method on the project object.

For extra properties, there is an "extra properties" section in the above groovy/javadoc for the Project object.

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