Java Gradle 中 $PROPERTY 的默认值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20694715/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Default value for a $PROPERTY in Gradle
提问by Zero Distraction
How can I specify a default value for this simple build.gradle
script:
如何为这个简单build.gradle
脚本指定默认值:
println "Hello $build_version"
So that I don't get the error:
这样我就不会收到错误消息:
A problem occurred evaluating root project 'hello_gradle'.
> Could not find property '$build_version' on root project 'hello_gradle'.
I tried some of the operators, checking for nulls etc, but I think just the reference to the property makes it fail. I could fix that by always providing the property, but that's less than ideal.
我尝试了一些运算符,检查空值等,但我认为只是对属性的引用使它失败。我可以通过始终提供属性来解决这个问题,但这并不理想。
gradle -Pbuild_version=World
采纳答案by Peter Niederwieser
if (!project.hasProperty("build_version")) {
ext.build_version = "1.0"
}
回答by Russ
This worked for me:
这对我有用:
def AWS_ACCESS_KEY="nokey"
def AWS_SECRET_KEY="nokey"
if (project.hasProperty("AWS_ACCESS_KEY")) {
AWS_ACCESS_KEY=project.get("AWS_ACCESS_KEY")
}
if (project.hasProperty("AWS_SECRET_KEY")) {
AWS_SECRET_KEY=project.get("AWS_SECRET_KEY")
}
回答by Micha? Skrzyński
This checks if the property exists and assigns a default value if not:
这将检查该属性是否存在,如果不存在则分配一个默认值:
def build_version=project.properties['build_version'] ?: "nokey"
回答by Fred Simon
I'm adding this to my build.gradle:
我将此添加到我的 build.gradle 中:
String propValue(String propName, String defValue) {
(project.hasProperty(propName) && project.getProperty(propName)) ? project.getProperty(propName) : defValue
}
then use when needed propValue('build_version', 'nokey')
.
然后在需要时使用propValue('build_version', 'nokey')
。
回答by MagMax
Have you tried this?:
你试过这个吗?:
println "Hello ${project.getProperty('build_version', 'default_string_value')}"
回答by zoomout
One-liner using ternary operator:
使用三元运算符的单行:
println "Hello ${project.hasProperty('build_version') ? getProperty('build_version') : 'World'}"
println "Hello ${project.hasProperty('build_version') ? getProperty('build_version') : 'World'}"
gradle <your_task> -Pbuild_version=SomethingElse
gradle <your_task> -Pbuild_version=SomethingElse