Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Gradle Goodness: Get Property Value With findProperty

DZone's Guide to

Gradle Goodness: Get Property Value With findProperty

Wonder what the difference between Gradle's "findProperty" and "property" methods are? Read on for the answer and how to use them properly.

· DevOps Zone
Free Resource

The DevOps Zone is brought to you in partnership with Sonatype Nexus. The Nexus Suite helps scale your DevOps delivery with continuous component intelligence integrated into development tools, including Eclipse, IntelliJ, Jenkins, Bamboo, SonarQube and more. Schedule a demo today

Gradle 2.13 added a new method to get a property value: findProperty. This method will return a property value if the property exists or null if the property cannot be found. Gradle also has the property method to return a property value, but this method will throw an exception if the property is missing. With the new findProperty method and the Groovy elvis operator (?:) we can try to get a property value and if not found return a default value.

In the following example we have a task that tries to print the value of the properties sampleOld and sampleNew. We use the findProperty for sampleNew and the property method for sampleOld:

// File: build.gradle
task resolveProperties ${project.hasProperty('sampleOld') ? project.property('sampleOld') : 'default value for sampleOld'}"
 println "sampleNew -> ${project.findProperty('sampleNew') ?: 'default value for sampleNew'}"
}

First run the task and not set the project properties sampleOld and sampleNew:

$ gradle -q resolveProperties
sampleOld -> default value for sampleOld
sampleNew -> default value for sampleNew
$

Next we use the -P command line option to set a value for the properties:

$ gradle -q -PsampleOld="Value sampleOld" -PsampleNew="Value sampleNew" resolveProperties
sampleOld -> Value sampleOld
sampleNew -> Value sampleNew
$

Written with Gradle 2.13.

The DevOps Zone is brought to you in partnership with Sonatype Nexus. Use the Nexus Suite to automate your software supply chain and ensure you're using the highest quality open source components at every step of the development lifecycle. Get Nexus today

Topics:
method ,property ,value ,gradle ,groovy

Published at DZone with permission of Hubert Klein Ikkink, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

THE DZONE NEWSLETTER

Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

X

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}