将命令行参数传递到运行任务中



https://stackoverflow.com/a/23689696/1757491

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

(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"

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

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

如果我忽略

-Dexec.args="arg1 arg2 arg3"

我得到

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

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

第一个

exec.args属性可以在主类中直接读取,因此根本不需要在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()
}

最新更新