Binary Plugin
Creating your own custom plugin might be a great solution when Gradle doesn’t offer the specific capabilities your project needs. This is where binary plugins come in.
A binary plugin is a plugin that is implemented in a compiled language and is packaged as a JAR file.
Binary plugins must implement the Plugin interface.
Implementing the Plugin Interface
For example, this is a very simple "Hello World" plugin:
abstract class SamplePlugin : Plugin<Project> { (1)
override fun apply(project: Project) { (2)
project.tasks.register("ScriptPlugin") {
doLast {
println("Hello world from the build file!")
}
}
}
}
apply<SamplePlugin>() (3)
class SamplePlugin implements Plugin<Project> { (1)
void apply(Project project) { (2)
project.tasks.register("ScriptPlugin") {
doLast {
println("Hello world from the build file!")
}
}
}
}
apply plugin: SamplePlugin (3)
| 1 | Extend the org.gradle.api.Plugin interface. |
| 2 | Override the apply method. |
| 3 | Apply the plugin to the project. |
1. Extend the org.gradle.api.Plugin interface
Create a class that extends the Plugin interface:
abstract class SamplePlugin : Plugin<Project> {
}
class SamplePlugin implements Plugin<Project> {
}
2. Override the apply method
Add tasks and other logic in the apply() method:
override fun apply(project: Project) {
}
void apply(Project project) {
}
3. Apply the plugin
Writing the plugin class does not apply it.
Because SamplePlugin is declared in the build script itself, it has no plugin ID, so it cannot be used in the plugins {} block.
Apply it by class instead:
apply<SamplePlugin>()
apply plugin: SamplePlugin
Gradle creates an instance of the plugin and calls its apply() method with the current Project.
In this example, that registers the ScriptPlugin task, so you can run it with ./gradlew ScriptPlugin.
A plugin declared in a build script is only visible in that script.
To share a plugin across projects, move it to buildSrc or an included build and give it an ID; see Creating a plugin ID.
Let’s take a look at a more realistic example next.
Next Step: Learn how to develop Binary Plugins >>