最佳答案
我试图将一个参数从命令行传递到 Java 类。我关注了这篇文章: http://gradle.1045684.n5.nabble.com/Gradle-application-plugin-question-td5539555.html,但是这段代码对我来说不起作用(也许它不是为 JavaExec 准备的?).以下是我试过的方法:
task listTests(type:JavaExec){
main = "util.TestGroupScanner"
classpath = sourceSets.util.runtimeClasspath
// this works...
args 'demo'
/*
// this does not work!
if (project.hasProperty("group")){
args group
}
*/
}
上面硬编码 args 值的输出如下:
C:\ws\svn\sqe\sandbox\selenium2forbg\testgradle>g listTests
:compileUtilJava UP-TO-DATE
:processUtilResources UP-TO-DATE
:utilClasses UP-TO-DATE
:listTests
Received argument: demo
BUILD SUCCESSFUL
Total time: 13.422 secs
但是,一旦我将代码更改为使用 hasProperty 部分并在命令行上将“ demo”作为参数传递,就会得到一个 NullPointerException:
C:\ws\svn\sqe\sandbox\selenium2forbg\testgradle>g listTests -Pgroup=demo -s
FAILURE: Build failed with an exception.
* Where:
Build file 'C:\ws\svn\sqe\sandbox\selenium2forbg\testgradle\build.gradle' line:25
* What went wrong:
A problem occurred evaluating root project 'testgradle'.
> java.lang.NullPointerException (no error message)
* Try:
Run with --info or --debug option to get more log output.
* Exception is:
org.gradle.api.GradleScriptException: A problem occurred evaluating root project
'testgradle'.
at org.gradle.groovy.scripts.internal.DefaultScriptRunnerFactory$ScriptRunnerImpl.run(DefaultScriptRunnerFactory.java:54)
at org.gradle.configuration.DefaultScriptPluginFactory$ScriptPluginImpl.apply(DefaultScriptPluginFactory.java:127)
at org.gradle.configuration.BuildScriptProcessor.evaluate(BuildScriptProcessor.java:38)
在 http://gradle.1045684.n5.nabble.com/file/n5709919/testgradle.zip上有一个简单的测试项目可以说明这个问题。
This is using Gradle 1.0-rc-3. The NullPointer is from this line of code:
args group
我在任务定义之前添加了以下任务,但它并没有改变结果:
group = hasProperty('group') ? group : 'nosuchgroup'
任何关于如何将命令行参数传递给 Gradle 的建议都值得赞赏。