Gradle Goodness: Run Java Application From Build Script

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.java
01.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.gradle
01.apply plugin: 'java'
02. 
03.task(runSimple, dependsOn: 'classes', type: JavaExec) {
04.main = 'com.mrhaki.java.Simple'
05.classpath = sourceSets.main.runtimeClasspath
06.args 'mrhaki'
07.systemProperty 'simple.message', 'Hello '
08.}
09. 
10.defaultTasks 'runSimple'
11. 
12.// javaexec() method also available for direct invocation
13.// javaexec {
14.//    main = 'com.mrhaki.java.Simple'
15.//    classpath = sourceSets.main.runtimeClasspath
16.//    args 'mrhaki'
17.//    systemProperty 'simple.message', 'Hello '
18.// }

We can execute our Gradle build script and get the following output:

00.$ gradle
01.:compileJava
02.:processResources
03.:classes
04.:runSimple
05.Hello mrhaki from Simple.
06. 
07.BUILD SUCCESSFUL
08. 
09.Total time: 4.525 secs