Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Gradle Goodness: Build Script Using Java Syntax

DZone's Guide to

Gradle Goodness: Build Script Using Java Syntax

A code snippet to teach Groovy developers how to build a script that understands Java code as well as Groovy code.

· Java Zone
Free Resource

Try Okta to add social login, MFA, and OpenID Connect support to your Java app in minutes. Create a free developer account today and never build auth again.

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.

Build and launch faster with Okta’s user management API. Register today for the free forever developer edition!

Topics:
gradle ,groovy ,java

Published at DZone with permission of Hubert Klein Ikkink, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}