Search code examples
javagradlegroovy

How are the destinationDirectory properties in the build.gradle Jar closure generated


I was confused when looking at the gradle source code. The destinationDirectory property in the AbstractArchiveTask is not declared AbstractArchiveTask, but why can it be called directly?

*archiveTask.destinationDirectory.set(new File(temporaryFolder.testDirectory, 'destinationDir'))* H

ow is this done?

The AbstractArchiveTask source code contains only methods and archiveDestinationDirectory attributes, but no destinationDirectory attributes.

    public DirectoryProperty getDestinationDirectory() {
        return archiveDestinationDirectory;
    }


Solution

  • The line of code you quoted is in AbstractArchiveTaskTest.groovy. This is Groovy code, not Java code.

    archiveTask.destinationDirectory is simply calling getDestinationDirectory declared in AbstractArchiveTask, as if it were a Groovy property. This is a syntactic sugar of Groovy. See also the Groovy documentation that talks about this.

    By convention, Groovy will recognize properties even if there is no backing field provided there are getters or setters that follow the Java Beans specification.

    The "Java Beans specification" is basically the convention where setters begin with set, and getters begins with get (or is for booleans). Groovy recognises these names and understands which method you want to call, when you access them like a property.