我有一个用Java编写的自定义Gradle任务,作为Gradle插件的一部分,它看起来像这样:
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;
这允许我调用以serviceVersion
为参数的任务,如下所示:
gradle myTask --serviceVersion="0.1"
我想让serviceVersion在某种程度上是可选的,如果没有指定值,那么默认为DEFAULT_SERVICE_VERSION
现在,它失败了:
> 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'.
如果没有指定任何值,我应该如何注释我的属性以使其默认为某个值?
只需在变量初始化时指定默认值:
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);
}
}
输出为:
$ ./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