Gradle to execute Java class (without changing build.gradle)

There is a simple Eclipse plugin to launch Gradle, which simply uses the command line method to start gradle.

What is the gradle analogue for compiling and running maven mvn compile exec:java -Dexec.mainClass=example.Example

Thus, any project with gradle.build can be launched.

UPDATE: there was a similar question. What is the gradle equivalent of the exec maven plugin for running Java applications? asked before, but a solution suggested changing every build.gradle project

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

Then doing 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 
+110
java gradle execution
Jan 26 '14 at 1:21
source share
3 answers

Use JavaExec . For example, put the following in build.gradle

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

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 dynamically on the command line. classpath set to select the latest classes.

If you do not pass in the mainClass property, this does not execute 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 complete the JavaExec task.

+126
Jan 26 '14 at 6:48
source share

You just need to use the Gradle Application Plugin :

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

And then just gradle run .

As Teresa points out, you can also configure mainClassName as a system property and run with a command line argument.

+135
Jan 26 '14 at 1:41
source share

gradle build answer to "First Zero," I think you need something where you can also run gradle build without errors.

Both gradle build and gradle -PmainClass=foo runApp work with this:

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

where you set the default main class.

+22
Feb 15 '17 at 20:37
source share



All Articles