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

Learn how to troubleshoot and diagnose some of the most common performance issues in Java today. Brought to you in partnership with AppDynamics.

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.

Understand the needs and benefits around implementing the right monitoring solution for a growing containerized market. Brought to you in partnership with AppDynamics.

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.

The best of DZone straight to your inbox.

SEE AN EXAMPLE
Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.
Subscribe

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

{{ parent.tldr }}

{{ parent.urlSource.name }}