如何使用“java”命令从 gradle 执行 jar 中的主类

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

How to execute a main class in a jar from gradle using the 'java' command

javagroovygradle

提问by JBT

I have these files under the <project_root>folder:

我在文件<project_root>夹下有这些文件:

./build.gradle
./build/libs/vh-1.0-SNAPSHOT.jar
./libs/groovy-all-2.1.7.jar
./src/main/groovy/vh/Main.groovy

In the build.gradlefile, I have this task:

build.gradle文件中,我有这个任务:

task vh( type:Exec ) {
    commandLine 'java -cp libs/groovy-all-2.1.7.jar:build/libs/' +
            project.name + '-' + version + '.jar vh.Main'
}

The Main.groovyfile is simple:

Main.groovy文件很简单:

package vh

class Main {
    static void main( String[] args ) {
        println 'Hello, World!'
    }

}

After plugging in the string values, the command line is:

插入字符串值后,命令行为:

java -cp libs/groovy-all-2.1.7.jar:build/libs/vh-1.0-SNAPSHOT.jar vh.Main

If I run the command directly from shell, I get correct output. However, if I run gradle vh, it will fail. So, how do I make it work? Thank you very much.

如果我直接从 shell 运行命令,我会得到正确的输出。但是,如果我运行gradle vh,它将失败。那么,我该如何让它发挥作用呢?非常感谢。

采纳答案by Peter Niederwieser

Exec.commandLineexpects a listof values: one value for the executable, and another value for each argument. To execute Java code, it's better to use the JavaExectask:

Exec.commandLine需要一个值列表:可执行文件的一个值,每个参数的另一个值。要执行 Java 代码,最好使用以下JavaExec任务:

task vh(type: JavaExec) {
    main = "vh.Main"
    classpath = files("libs/groovy-all-2.1.7.jar", "build/libs/${project.name}-${version}.jar")
} 

Typically, you wouldn't have to hardcode the class path like that. For example, if you are using the groovyplugin, and groovy-allis already declared as a compiledependency (and knowing that the second Jar is created from the mainsources), you would rather do:

通常,您不必像那样对类路径进行硬编码。例如,如果您正在使用groovy插件,并且groovy-all已经声明为compile依赖项(并且知道第二个 Jar 是从main源创建的),您宁愿这样做:

classpath = sourceSets.main.runtimeClasspath

To find out more about the Execand JavaExectask types, consult the Gradle Build Language Reference.

要了解有关任务类型ExecJavaExec任务类型的更多信息,请参阅Gradle 构建语言参考