Gradle
has a special task to run a Java class from the build script: org.gradle.api.tasks.JavaExec.
We can for example create a new task of type JavaExec and use a closure to configure the
task. We can set the main class, classpath, arguments, JVM arguments and more to
run the application.
Gradle
also has the javaexec() method available as part of a Gradle
project. This means we can invoke javaexec() directly from the build script and use
the same closure to configure the Java application that we want to invoke.
Suppose we have a simple Java application:
00.//
File: src/main/java/com/mrhaki/java/Simple.java01.package com.mrhaki.java;02. 03.public class Simple
{04. 05.public static void main(String[]
args) {06.System.out.println(System.getProperty("simple.message")
+ args[0]
+ "
from Simple.");07.}08. 09.}And
we have the following Gradle build file to run Simple:
00.//
File: build.gradle01.apply
plugin: 'java'02. 03.task(runSimple,
dependsOn: 'classes',
type: JavaExec) {04.main
= 'com.mrhaki.java.Simple'05.classpath
= sourceSets.main.runtimeClasspath06.args 'mrhaki'07.systemProperty 'simple.message', 'Hello
'08.}09. 10.defaultTasks 'runSimple'11. 12.//
javaexec() method also available for direct
invocation13.//
javaexec {14.//
main = 'com.mrhaki.java.Simple'15.//
classpath = sourceSets.main.runtimeClasspath16.//
args 'mrhaki'17.//
systemProperty 'simple.message', 'Hello '18.//
}We can execute our Gradle build script and get the following output:
00.$
gradle01.:compileJava02.:processResources03.:classes04.:runSimple05.Hello
mrhaki from Simple.06. 07.BUILD
SUCCESSFUL08. 09.Total
time: 4.525 secs