September 24, 2010

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:

// File: src/main/java/com/mrhaki/java/Simple.java
package com.mrhaki.java;

public class Simple {

    public static void main(String[] args) {
        System.out.println(System.getProperty("simple.message") + args[0] + " from Simple.");


And we have the following Gradle build file to run Simple:

// File: build.gradle
apply plugin: 'java'

task(runSimple, dependsOn: 'classes', type: JavaExec) {
    main = 'com.mrhaki.java.Simple'
    classpath = sourceSets.main.runtimeClasspath
    args 'mrhaki'
    systemProperty 'simple.message', 'Hello '

defaultTasks 'runSimple'

// javaexec() method also available for direct invocation
// javaexec {
//    main = 'com.mrhaki.java.Simple'
//    classpath = sourceSets.main.runtimeClasspath
//    args 'mrhaki'
//    systemProperty 'simple.message', 'Hello '
// }

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

$ gradle
Hello mrhaki from Simple.


Total time: 4.525 secs