DevOps / Gradle8 Interview Questions
How do you implement a custom Gradle task?
A custom task is a Java or Groovy/Kotlin class extending DefaultTask, with its configurable inputs and outputs declared as annotated properties, and its behavior defined in a method annotated @TaskAction.
abstract class GreetTask extends DefaultTask { @Input abstract Property<String> getName() @OutputFile abstract RegularFileProperty getOutputFile() @TaskAction void greet() { outputFile.get().asFile.text = "Hello, ${name.get()}!" } } tasks.register('greet', GreetTask) { name = 'World' outputFile = layout.buildDirectory.file('greeting.txt') }
Using the abstract-class-with-Property pattern (rather than plain fields) is what makes the task compatible with the configuration cache and lazy configuration — Gradle generates the property implementation and can track it properly for up-to-date checks and serialization. This is the recommended, modern approach over the older pattern of writing a task inline as an ad-hoc closure, since a proper task class is reusable, testable, and correctly integrates with Gradle's incremental-build and caching machinery.
More Related questions...
