I've got a custom Gradle task written in Java as part of a Gradle plugin that look like this:
public abstract class MyTask extends DefaultTask {
private static final String DEFAULT_SERVICE_VERSION = "NO VERSION";
private String serviceVersion;
@Option(option = "serviceVersion", description = "Configures the service version.")
public void setServiceVersion(String serviceVersion) {
this.serviceVersion = serviceVersion;
}
@Input
public String getServiceVersion() {
return serviceVersion;
}
@TaskAction
public void myTask() {
String serviceVersionCurrent = getServiceVersion() != null ? getServiceVersion() : DEFAULT_SERVICE_VERSION;
This allows me to call the task with serviceVersion
as parameter as follows:
gradle myTask --serviceVersion="0.1"
I would like to make serviceVersion somehow optional and if no value is specified, then default to DEFAULT_SERVICE_VERSION
As it is now, it fails:
> gradle myTask
> Task :myTask FAILED
FAILURE: Build failed with an exception.
* What went wrong:
Some problems were found with the configuration of task ':myTask' (type 'MyTask').
> No value has been specified for property 'serviceVersion'.
How should I annotate my property to make it default to a certain value if none is specified?
Just assign the default value at the variable initialization:
public class GreetingTask extends DefaultTask {
private String serviceVersion = "v1.0";
@Option(option = "serviceVersion", description = "Configure service version")
public void setServiceVersion(String serviceVersion) {
this.serviceVersion = serviceVersion;
}
@Input
public String getServiceVersion() {
return this.serviceVersion;
}
@TaskAction
public void task() {
System.out.println(this.serviceVersion);
}
}
The output would be:
$ ./gradlew greeting
> Task :greeting
v1.0
BUILD SUCCESSFUL in 2s
3 actionable tasks: 3 executed
$ ./gradlew greeting --serviceVersion=v2.0
> Task :greeting
v2.0
BUILD SUCCESSFUL in 1s
3 actionable tasks: 1 executed, 2 up-to-date
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.