Gradle Programming TODEPLETE: Difference between revisions
m (Ovidiu moved page Gradle Programming to Gradle Programming TODEPLETE without leaving a redirect) |
|
(No difference)
|
Latest revision as of 00:09, 9 November 2020
Internal
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
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])
}
}