Search code examples
javagradlejarbuildbuild.gradle

Is Gradles `jar` a method?


I'm using the Java Plugin in Gradle

apply plugin: 'java'

I also configure the Jar-task using:

version = '1.0'
jar {
    manifest {
        attributes 'Implementation-Title': 'Gradle Quickstart',
                   'Implementation-Version': version
    }
}

If I understood it right, jar is a method which is called with a closure as the parameter. But where is this method documented? I my understandung it schuld be a method of Project.

I couldn't find it in https://docs.gradle.org/current/userguide/java_plugin.html and https://docs.gradle.org/current/dsl/org.gradle.api.Project.html and https://docs.gradle.org/current/dsl/org.gradle.api.tasks.bundling.Jar.html

Or am I wrong with my assumption that jar is a method?


Solution

  • The answer is yes and no. The syntax is syntactic sugar (although in this case it makes things confusing). It is not a function jar that is called, but the function tasks.getByName that gets the name and the closure as a parameter.

    On https://docs.gradle.org/current/userguide/more_about_tasks.html it says in part 17.3. Configuring tasks (Example 17.9. Configuring a task - with closure):

    This works for any task. Line 3 of the example is just a shortcut for the tasks.getByName() method. It is important to note that if you pass a closure to the getByName() method, this closure is applied to configure the task, not when the task executes.

    So you can also write:

    version = '1.0'
    tasks.getByName "jar", {
        manifest {
            attributes 'Implementation-Title': 'Gradle Quickstart',
                       'Implementation-Version': version
        }
    }