Gradle Programming TODEPLETE: Difference between revisions

From NovaOrdis Knowledge Base
Jump to navigation Jump to search
Line 56: Line 56:
t.applicationName = 'something';
t.applicationName = 'something';
t.mainClassName = 'com.example.Main';
t.mainClassName = 'com.example.Main';
</syntaxhighlight>
=Imports=
A build.gradle file accepts an import declaration section, in case we need to use Java classes:
<syntaxhighlight lang='groovy'>
import java.nio.file.Files
...
task someTask {
  doFirst {
    Files.write(file.toPath(), new byte[0])
  }
}
</syntaxhighlight>
</syntaxhighlight>



Revision as of 07:11, 28 February 2019

Internal

Groovy

Groovy

Projects

Inter-Project "Communication"

The Project is the main API to use to interact with Gradle, so a great deal of custom configuration can be achieved getting a hold of a project reference and reading state from it or invoking into it from the build.gradle files. The reference to the current project can be obtained by using getProject() in the corresponding build.gradle file, which is equivalent with invoking 'project'

println project

A project reference can be used to get references to other Projects in the tree and thus navigate the hierarchy.

For all projects in the hierarchy, the reference to the root project can be obtained by invoking 'project.getRootProject()', or simply 'rootProject'.

println rootProject

For a sub-project, a reference to the parent project can be obtained by invoking 'project.getParent()', or simply 'parent'.

println parent

Tasks

Gradle Task

Obtaining a Task Reference

Task task = project.getTasksByName("build", false).asList().get(0)

Re-evaluate this.

The reference of a specific task may be obtained with findByPath("..."), which returns null if the task does not exist, or getByPath("..."), which throws UnknownTaskException if the task does not exist.

rootProject.tasks.findByPath('startScripts').mainClassName = 'com.example.Main';

If we need to change the value of several member variables, it is cleaner to keep the reference to the task in a local variable and use that reference to change state:

def org.gradle.api.Task t = rootProject.tasks.getByPath('startScripts');
t.applicationName = 'something';
t.mainClassName = 'com.example.Main';

Imports

A build.gradle file accepts an import declaration section, in case we need to use Java classes:

import java.nio.file.Files
...
task someTask {

  doFirst {

    Files.write(file.toPath(), new byte[0])
  }
}

Recipes

Task that Prints the Execution Classpath

Print the Runtime Classpath

Obtain and Use Gradle Version in build.gradle

Gradle Object - Gradle Version