Java › Build Tools: Maven & Gradle

How would you write a custom Maven plugin or Gradle task to perform project-specific build automation not covered by existing plugins?

Advanced

Answer

A custom Maven plugin requires implementing AbstractMojo (annotated with @Mojo specifying the goal name), overriding execute() with your custom logic, packaged and installed as its own separate Maven artifact before being usable in a project's pom.xml; a custom Gradle task is comparatively lightweight, defined directly inline in build.gradle.kts by extending DefaultTask and annotating an action method with @TaskAction, without needing a separate publishing step for simple, project-local automation -- Gradle's approach is generally considered more approachable for one-off, project-specific automation, while Maven's plugin model suits more broadly reusable, formally-published automation.
// Custom Gradle task, defined directly in build.gradle.kts
abstract class GenerateVersionFile : DefaultTask() {
    @TaskAction
    fun generate() {
        val versionFile = File(project.buildDir, "version.txt")
        versionFile.writeText(project.version.toString())
    }
}

tasks.register<GenerateVersionFile>("generateVersionFile")
tasks.named("build") { dependsOn("generateVersionFile") }
Real-world example A team needing to generate a build metadata file (git commit hash, build timestamp) before packaging writes a lightweight custom Gradle task directly in their build script, avoiding the overhead of publishing a separate Maven plugin artifact just for this one project-specific, non-reusable piece of automation.

Common follow-ups: What's the process for publishing a custom Maven plugin so other projects/teams can reuse it?;How does Gradle's task dependency graph (dependsOn, mustRunAfter) let you control custom task execution order relative to built-in tasks?