首页 文章

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

提问于
浏览
96

simple Eclipse plugin运行Gradle,它只使用命令行方式启动gradle .

什么是graven模拟maven编译并运行 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

3 回答

  • 116

    使用 JavaExec . 作为一个例子,将以下内容放在 build.gradle

    task execute(type:JavaExec) {
       main = mainClass
       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'.
    

    评论更新:

    gradle中没有 mvn exec:java 等效项,您需要应用应用程序插件或具有JavaExec任务 .

  • 12

    你只需要使用Gradle Application plugin

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

    然后只需 gradle run .

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

  • 109

    在First Zero上扩展's answer, I'我猜你想要的东西你也可以运行 gradle build 而不会出错 .

    gradle buildgradle -PmainClass=foo runApp 都适用于此:

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

    您在哪里设置默认主类 .

相关问题