Gradle执行Java类(不修改build.gradle)

新手上路,请多包涵

有一个 简单的 Eclipse 插件 来运行 Gradle,它只使用命令行方式启动 gradle。

什么是maven编译和运行的gradle模拟 mvn compile exec:java -Dexec.mainClass=example.Example

这样任何带有 gradle.build 的项目都可以运行。

更新:有类似的问题 What is the gradle equivalent of maven’s exec plugin for running Java apps? 之前问过,但解决方案建议更改每个项目 build.gradle

 package runclass;

public class RunClass {
    public static void main(String[] args) {
        System.out.println("app is running!");
    }
}

然后执行 gradle run -DmainClass=runclass.RunClass

 :run FAILED

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':run'.
> No main class specified

原文由 Paul Verest 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 570
2 个回答

在gradle中没有直接等同于 mvn exec:java ,你需要应用 application 插件或者有一个 JavaExec

application 插件

激活插件:

 plugins {
    id 'application'
    ...
}

配置如下:

 application {
    mainClassName = project.hasProperty("mainClass") ? project.getProperty("mainClass") : "NULL"
}

在命令行中,写

$ gradle -PmainClass=Boo run

JavaExec 任务

定义一个任务,比方说 execute

 task execute(type:JavaExec) {
   main = project.hasProperty("mainClass") ? getProperty("mainClass") : "NULL"
   classpath = sourceSets.main.runtimeClasspath
}

要运行,请编写 gradle -PmainClass=Boo execute 。你得到

$ gradle -PmainClass=Boo execute
:compileJava
:compileGroovy UP-TO-DATE
:processResources UP-TO-DATE
:classes
:execute
I am BOO!

mainClass 是命令行动态传入的属性。 classpath 设置为上最新课程。


如果您不传入 mainClass 属性,这两种方法都会按预期失败。

 $ gradle execute

FAILURE: Build failed with an exception.

* Where:
Build file 'xxxx/build.gradle' line: 4

* What went wrong:
A problem occurred evaluating root project 'Foo'.
> Could not find property 'mainClass' on task ':execute'.

原文由 First Zero 发布,翻译遵循 CC BY-SA 4.0 许可协议

您只需要使用 Gradle Application 插件

 apply plugin:'application'
mainClass = "org.gradle.sample.Main"

然后简单地 gradle run

正如 Teresa 指出的那样,您还可以将 mainClass 配置为系统属性并使用命令行参数运行。

原文由 Vidya 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题