Java 如何使用Gradle将参数传递给main方法?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22423677/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 15:38:26  来源:igfitidea点击:

How to pass parameters to main method using Gradle?

javagradlemaincommandargument

提问by Xelian

I have to pass two arguments to my main method. My build script is

我必须将两个参数传递给我的 main 方法。我的构建脚本是

// 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

}

If I try:

如果我尝试:

gradlew main doc.json text.txt

Then an error occured.

然后发生了错误。

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

How can I pass arguments to my main method command line easily?

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

采纳答案by Erik Pragt

You should use use -P as listed in the Gradle command line documentation.

您应该使用 Gradle命令行文档中列出的 -P 。

For example, the following will work:

例如,以下将起作用:

gradlew main -Parg1=doc.json --project-prop arg2=text.txt

And you access them in your Gradle script like this:

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

println "$arg1 $arg2"

回答by juliocesarfx

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

回答by Ravikumar

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"