如何使用Gradle向主方法传递参数?

15

我必须向我的主方法传递两个参数。我的构建脚本是:

// Apply the java plugin to add support for Java
apply plugin: 'java'

// In this section you declare where to find the dependencies of your project
repositories {
    // Use 'maven central' for resolving your dependencies.
    mavenCentral()
}

// In this section you declare the dependencies for your production and test code
dependencies {
    compile 'com.example:example-core:1.7.6'
}

task main(type: JavaExec, dependsOn: classes) {
    description = 'This task will start the main class of the example project'
    group = 'Example'
    main = 'com.example.core.Example'
    classpath = sourceSets.main.runtimeClasspath

}

如果我尝试:

gradlew main doc.json text.txt

然后发生了一个错误。

org.gradle.execution.TaskSelectionException: Task 'doc.json' not found in root project

如何轻松地通过命令行将参数传递给我的主方法?


2
请参阅https://dev59.com/emgt5IYBdhLWcg3w8h41/。 - Joshua Goldberg
3个回答

14
task run(type: JavaExec) {
    main = "pkg.MainClass"
    classpath = sourceSets.main.runtimeClasspath
    args = ["arg1", "arg2"]
}

6
你应该使用Gradle 命令行文档中列出的-P选项。
例如,以下命令可以正常工作:
gradlew main -Parg1=doc.json --project-prop arg2=text.txt

你可以像这样在Gradle脚本中访问它们:

println "$arg1 $arg2"

-Pargs="doc.json,text.txt" 或者如何将此系统属性传递给主方法? - Xelian
好的,那么如何将它们传递给主方法呢? - Xelian
1
请查看http://www.gradle.org/docs/current/dsl/org.gradle.api.tasks.JavaExec.html。检查“args”属性。 - Erik Pragt
1
在主函数中添加:args = ["$arg1", "$arg2"]。谢谢@Erik。 - Xelian

2
task run1(type: JavaExec) {
    main = "pkg.mainclass"
    classpath = sourceSets.main.runtimeClasspath
    args = ["$arg1","$arg2",...]
}

//I have named as run1 it can be any task name

While invoking the gradle script:
c:\> gradle run1 -Parg1="test123" -Parg2="sss"

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接