Nicolas Rouquette
Nicolas Rouquette

Reputation: 458

How to provide the value of a @Nested property of a gradle task?

The gradle doc describes the @Nested annotation for custom gradle tasks: https://docs.gradle.org/current/userguide/more_about_tasks.html#sec:task_input_output_annotations

Unfortunately, there is no complete example of this mechanism in terms of how it is used in a build.gradle file. I created a project to demonstrate a strange exception that happens whenever gradle configures the project: https://github.com/NicolasRouquette/gradle-nested-property-test

The build.gradle has the following:

task T(type: NestedTest) {
    tool = file('x')
    metadata = {
        a = "1"
    }
}

The NestedTest custom task is in the buildSrc folder:

class NestedTest extends DefaultTask {

    @InputFile
    public File tool

    @Nested
    @Input
    public Metadata metadata

    @TaskAction
    def run() throws IOException {
        // do something...
    }
}

The important bit is the @Nested property whose type is really basic:

class Mlang-groovyetadata {
    String a
}

When I execute the following: ./gradlew tasks, I get this:

Build file '/opt/local/github.me/gradle-nested-property-test/build.gradle' line: 26

* What went wrong:
A problem occurred evaluating root project 'gradle-nested-property-test'.
> Cannot cast object 'build_6wy0cf8fn1e9nrlxf3vmxnl5z$_run_closure4$_closure5@2bde737' with class 'build_6wy0cf8fn1e9nrlxf3vmxnl5z$_run_closure4$_closure5' to class 'Metadata'

Can anyone explain what is happening and how to make this work?

Upvotes: 0

Views: 572

Answers (1)

Nicolas Rouquette
Nicolas Rouquette

Reputation: 458

Looking at the unit tests in Gradle's source code, I found that the syntax for @Nested properties requires invoking the type constructor in the build.gradle file.

That is, the following works:

task T(type: NestedTest) {
    tool = file('x')
    metadata = new Metadata(
        a: "1"
    )
}

Upvotes: 0

Related Questions