Gradle, creating objects in build.gradle scripts

In my gradle plugin, I am using another build.gradle

script that looks like this:

build.gradle:

sciptInstance {
    name {
        arrayWithObjects = [
            {
                var1 = "val1"
                var2 = "val2"
            {
        ]
    }
}

      

In the gradle plugin, I have declared a container for storing class instances ScriptClass

. This class has a field arrayWithObjects

. The element class declaration arrayWithObjects

looks like this:

MyClass {
    def var1
    deg var2
}

      

In my SciptClass

:

ScriptClass {
    // other fields
    MyClass[] arrayWithObjects

    // constructor and so on..
}

      

When trying to build a script, I get a casting exception saying that I cannot use object closure. I tried to declare arrayWithObjects

in build.gradle

with other brackets, etc., but nothing really works. I also don't know where to look for it. Perhaps some of you have encountered this problem before? Thanks in advance.

EDIT: To reproduce this:

Plugin:

apply plugin: MyPlugin

apply from: 'example.gradle'

class MyPlugin implements Plugin<Project> {
    void apply(Project project) {
        def examples = project.container(ScriptClass)
        project.extensions.examples = examples
    }
}

class ScriptClass {
    String name
    MyClass[] arrayWithObjects

    ScriptClass(String name) {
        this.name = name
    }
}

class MyClass {
    def var1
    def var2
}

      

example.gradle:

examples {
    example {
        arrayWithObjects = [
                {
                    var1 = "val1"
                    var2 = "val2"
                }
        ]
    }
}

      

In the main, build.gradle

apply this plugin and invoke any task.

+3


source to share


1 answer


Here you can find the demo, which solves the problem. Basically you need to use Map

instead Closure

:



examples {
    example {
        arrayWithObjects = [
                [var1: 'varvar1', var2: 'varvar2']
        ]
    }
}

      

+2


source







All Articles