Gradle Extra Properties: Difference between revisions
Line 4: | Line 4: | ||
An '''extra property''' is a property that can be declared on most model object instances available to the closure being executed. Extra properties allow defining variables that are used multiple times within the same script, such as a file that is referred from multiple locations of the build script. An extra property is equivalent to a user-defined variable. Internally, extra properties are stored as key-value pairs in a map, associated with the model object instance, most notably the project instance. | An '''extra property''' is a property that can be declared on most model object instances available to the closure being executed. Extra properties allow defining variables that are used multiple times within the same script, such as a file that is referred from multiple locations of the build script. An extra property is equivalent to a user-defined variable. Internally, extra properties are stored as key-value pairs in a map, associated with the model object instance, most notably the project instance. | ||
To add properties, use | To add properties, use an "ext" namespace closure: | ||
<syntaxhighlight lang='groovy'> | <syntaxhighlight lang='groovy'> | ||
ext { | ext { | ||
color = 'blue' | color = 'blue' | ||
} | } | ||
</syntaxhighlight> | |||
An equivalent assignment is: | |||
<syntaxhighlight lang='groovy'> | |||
project.ext.color = 'blue' | |||
} | |||
</syntaxhighlight> | |||
<syntaxhighlight lang='groovy'> | |||
project.ext.color = 'green' | project.ext.color = 'green' | ||
project.color = 'red' // project.ext.color and project.color are equivalent after property initialization | project.color = 'red' // project.ext.color and project.color are equivalent after property initialization |
Revision as of 03:48, 5 October 2020
Internal
Overview
An extra property is a property that can be declared on most model object instances available to the closure being executed. Extra properties allow defining variables that are used multiple times within the same script, such as a file that is referred from multiple locations of the build script. An extra property is equivalent to a user-defined variable. Internally, extra properties are stored as key-value pairs in a map, associated with the model object instance, most notably the project instance.
To add properties, use an "ext" namespace closure:
ext {
color = 'blue'
}
An equivalent assignment is:
project.ext.color = 'blue'
}
project.ext.color = 'green'
project.color = 'red' // project.ext.color and project.color are equivalent after property initialization
task displayColor {
doLast {
println project.ext.color
println project.color
println color
}
}
For the above example, ./gradlew displayColor
will display "red".
Note that the "ext" script block or project.ext
syntax must only be used at declaration, for subsequent access the extra property can be looked up directly on the project instance.