15
votes

I admit I am quite new to gradle but I did not expect to be unable to understand something as simple as the example below. I can read the gradle documentation about checking whether a project property have been set or not using a hasProperty(String propertyName) call and I am sitting here and have no idea why something so basic does not work.

I believe my mind must be so much "ant like" oriented that for sure I am missing something ordinary basic

task printSystem() << {
    println system
    println "has property: " + hasProperty("system")
}

and invoking that task with the command below:

$gradle printSystem -Psystem=mySystem
mySystem
has property: null

So my questions would be:

  1. Why system is printed out but hasProperty returns null?
  2. How should I check for the existence of the project property called "system"?
  3. Is there a different way for testing for a project property as opposed to a system property?
  4. How would you pass a system property from the command line?

This is from, the gradle documentation and I believe I am reading it right

19.2.1. Checking for project properties

You can access a project property in your build script simply by using its name as you would use a variable. If this property does not exist, an exception will be thrown and the build will fail. If your build script relies on optional properties the user might set, perhaps in a gradle.properties file, you need to check for existence before you access them. You can do this by using the method hasProperty('propertyName') which returns true or false.

1
Have you seen my answer? Does it solve he problem? If so, please accept it. - Opal
Your answer arrived on a Friday afternoon when I was enjoying an end of week drink with my office colleagues :-) I tested your solution today and it worked. I wished the documentation would be clearer say just by putting project.hasProperty('propertyName') as opposed to what it shows now. Also when something is supposed to return true or false and returns a null instead adds on to the confusion. Thank you very much. - Julian

1 Answers

19
votes

You need to explicitly invoke hasProperty on the project instance - without it, hasProperty is invoked on some local context. The following example works:

task printSystem() << {
    println system
    println "has property: " + project.hasProperty("system")
}
  1. Because non-existing properties (system is not defined in the script) are taken from the project instance. If you won't pass the system property, an exception will be thrown on println.
  2. project.hasProperty('propName')
  3. Not sure if I understood right, but you can access project properties via the project instance and system properties via the System class.
  4. Using -D switch - gradle -Dprop=value