Gradle error: Could not find method jar() for arguments

Viewed 5598

I'm writing a custom plugin which adds some data to manifest of Java project.

It looks something like this:

package com.example.gradle

import org.gradle.api.Plugin
import org.gradle.api.Project

public class ExamplePlugin implements Plugin<Project> {

    def apply(Project project) {
        project.jar() {
            manifest {
                attributes 'buildServer': checkIfIsBuildServer()
                attributes 'personalBuild': checkIfIsPersonalBuild()
            }
        }
    }

    def checkIfIsBuildServer() {
        return 'some result'
    }

    def checkIfIsPersonalBuild() {
        return 'some result'
    }

}

When I'm trying to apply it to some project, I get an error:

Could not find method jar() for arguments [com.example.gradle.ExamplePlugin$_apply_closure1@411e4f5e] on project ':SomeProject' of type org.gradle.api.Project.

I am reasonably sure this is some missing import. I don't have any idea how to determine what import it should be.

1 Answers

jar() isn’t a method on Project.

If I’m understanding your code correctly, what you are trying to do is configure the jar task that is created from the Java Plugin.

So you need to:

  1. Get the task
  2. Configure the task

Something like:

import org.gradle.api.plugins.JavaPlugin
import org.gradle.api.tasks.bundling.Jar

public class ExamplePlugin implements Plugin<Project> {
    def apply(Project project) {
        project.afterEvaluate {
            project.tasks.named(JavaPlugin.JAR_TASK_NAME, Jar) {
                it.manifest {
                    attributes 'buildServer': checkIfIsBuildServer()
                    attributes 'personalBuild': checkIfIsPersonalBuild()
                }
            }
        }
    }

    def checkIfIsBuildServer() {
        'some result'
    }

    def checkIfIsPersonalBuild() {
        'some result'
    }
}

I highly recommend switch to Kotlin or Java for your plugin. It will make errors like this trivial to resolve and you will fully understand where things are coming from compared to Groovy’s dynamic nature.

Related