本文介绍了Gradle执行Java类(不修改build.gradle)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有运行Gradle,它只是使用命令行方式来启动gradle。



maven编译和运行的gradle模拟是什么
使用 JavaExec 。举例如下: build.gradle

  task execute(类型:JavaExec){
main = mainClass
classpath = sourceSets.main.runtimeClasspath
}

运行 gradle -PmainClass = Boo执行。你得到

  $ gradle -PmainClass = Boo执行
:compileJava
:compileGroovy UP-TO-DATE
:processResources UP-TO-DATE
:类
:执行
我是BOO!

mainClass 是一个属性,命令行。 classpath 设置为拾取最新的类。



如果不传入

  $ gradle execute 

失败:生成失败,出现异常。

*其中:
构建文件'xxxx / build.gradle'行:4

*出错:
评估根项目时出现问题富。
>无法在任务'execute'上找到属性'mainClass'。

更新来自评论:

在Gradle中没有 mvn exec:java 等价,您需要应用应用程序插件或者执行JavaExec任务。


There is simple Eclipse plugin to run Gradle, that just uses command line way to launch gradle.

What is gradle analog for maven compile and runmvn compile exec:java -Dexec.mainClass=example.Example

This way any project with gradle.build could be run.

UPDATE: There was similar question What is the gradle equivalent of maven's exec plugin for running Java apps? asked before, but solution suggested altering every project build.gradle

package runclass;

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

Then executing 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
解决方案

Use JavaExec. As an example put the following in build.gradle

task execute(type:JavaExec) {
   main = mainClass
   classpath = sourceSets.main.runtimeClasspath
}

To run gradle -PmainClass=Boo execute. You get

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

mainClass is a property passed in dynamically at command line. classpath is set to pickup the latest classes.

If you do not pass in the mainClass property, this fails as expected.

$ 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'.

UPDATED from comments:

There is no mvn exec:java equivalent in gradle, you need to either apply the application plugin or have a JavaExec task.

这篇关于Gradle执行Java类(不修改build.gradle)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-05 20:57