A Gradle build script is actually a Groovy script. The Gradle API uses Groovy a lot so we can have a nice DSL to define our builds. But we can also use Java code in a Groovy script. The compiler that compiles the build script understands Java code as well as the Groovy code. Sometimes I hear from people new to Gradle that they have difficulty understanding the DSL. I thought it would be a fun exercise to write a very simple Gradle build script using Java syntax.

Most notable is that we invoke the getProject method to get a reference to org.grade.api.Project. In the Gradle DSL we could use the simpler Groovy property reference project or just leave it out, because all method invocations in the build script are delegated to Project.

// Apply Java plugin.
getProject().getPluginManager().apply("java");

// Set repositories.
final RepositoryHandler repositories = getProject().getRepositories();
repositories.jcenter();

// Set dependencies.
final DependencyHandler dependencies = getProject().getDependencies();
dependencies.add("compile", "org.slf4j:slf4j-api:1.7.14");
dependencies.add("testCompile", "junit:junit:4.12");

// Add a new task.
final TaskContainer tasks = getProject().getTasks();
final Task helloWorldTask = tasks.create("helloWorld");
helloWorldTask.doFirst(new Action() {
    void execute(Object task) {
        System.out.println("Running " + task.getName());
    }
});


/* Equivalent to following Gradle DSL:

apply plugin: 'java'

repositories {
    jcenter()
}

dependencies {
    compile 'org.slf4j:slf4j-api:1.7.14'
    testCompile 'junit:junit:4.12'
}

task helloWorld << { task ->
    println "Running $task.name"
}
*/

Written with Gradle 2.11.

Original blog post

shadow-left