如何使用“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
How to execute a main class in a jar from gradle using the 'java' command
提问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.gradle
file, 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.groovy
file 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.commandLine
expects a listof values: one value for the executable, and another value for each argument. To execute Java code, it's better to use the JavaExec
task:
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 groovy
plugin, and groovy-all
is already declared as a compile
dependency (and knowing that the second Jar is created from the main
sources), you would rather do:
通常,您不必像那样对类路径进行硬编码。例如,如果您正在使用groovy
插件,并且groovy-all
已经声明为compile
依赖项(并且知道第二个 Jar 是从main
源创建的),您宁愿这样做:
classpath = sourceSets.main.runtimeClasspath
To find out more about the Exec
and JavaExec
task types, consult the Gradle Build Language Reference.
要了解有关任务类型Exec
和JavaExec
任务类型的更多信息,请参阅Gradle 构建语言参考。