将命令行参数传递给 运行 任务

Pass command line parameters into run task

我开始使用上述答案中建议的解决方案中的一些信息: 应用程序插件方法

(build.gradle)

 apply plugin: 'application'

 mainClassName = "com.mycompany.MyMain"
 run { 
    /* Need to split the space-delimited value in the exec.args */
   args System.getProperty("exec.args").split()    
}

命令行:

gradle run -Dexec.args="arg1 arg2 arg3"

它非常适合预期目的,但似乎有副作用。为 运行 传递命令行参数是有意义的,但我必须为每个任务传递它们,例如:

gradle tasks -Dexec.args="arg1 arg2 arg3"

如果我省略

-Dexec.args="arg1 arg2 arg3"

我明白了

"build failed with an exception"
Where:path\build.gradle line:18 which if where my run{ } is.

你可以用两种不同的方法解决它:

第一个:

exec.args 属性 可以直接在主 class 中读取 - 所以根本不需要在 run 闭包中配置 args

第二:

只要如果它:

execArgs = System.getProperty('exec.args') 
if(execArgs)    
   args = execArgs.split()

提问者编辑: 使用 if 确实有效,但我不得不稍微更改语法。

if(System.getProperty("exec.args") != null) {
    args System.getProperty("exec.args").split()
}