Declare array/hashmap in gradle.properties file

I'm trying to define an array in the gradle.properties file. When, for example, I do the next in some gradle script:

project.ext.mygroup = [
  myelement1: "myvalue1",
  myelement2: "myvalue2"
]
project.mygroup.put("myelement3", "myvalue3"); // As internally it works like a hashmap

and then I list the properties, I get:

mygroup: {myelement1=myvalue1, myelement2=myvalue2, myelement3=myvalue3}

So, if I try setting a property with the same form in the gradle.properties file:

mytestgroup={myelement1=myvalue1, myelement2=myvalue2}

And then in the gradle script I try to access this property:

project.mytestgroup.put("myelement3", "myvalue3");

I get the next error:

No signature of method: java.lang.String.put() is applicable for argument types: (java.lang.String, java.lang.String) values: [myelement3, myvalue3]

This is because the property "mytestgroup" is being taken as a string instead of an array.

Does any one know what is the correct syntax to declare an array in the gradle.properties file?

Thanks in advance


The notation {myelement1=myvalue1, myelement2=myvalue2, myelement3=myvalue3} is simply a string representation of the object as the result of calling Map.toString() . It is not syntactically correct Groovy.

Your first example is the correct way to define a Map .

def myMap = [ key : 'value' ]

Defining an array is similar.

def myArray = [ 'val1', 'val2', 'val3' ]

Set the property to JSON string

myHash = {"first": "Franklin", "last": "Yu"}
myArray = [2, 3, 5]

and parse it in build script with JsonSlurper:

def slurper = new groovy.json.JsonSlurper()
slurper.parseText(hash) // => a hashmap
slurper.parseText(array) // => an array

The JsonSlurper way is good, but I wanted a cleaner way to define both a simple string or an array as a property. I solved it by declaring the property as:

mygroup=myvalue1

or:

mygroup=myvalue1,myvalue2,myvalue3

Then inside Gradle retrieve the property with:

Properties props = new Properties()
props.load(new FileInputStream(file('myproject.properties')))
props.getProperty('mygroup').split(",")

And you will get an array of String. Be careful with space characters around the commas.

链接地址: http://www.djcxy.com/p/82220.html

上一篇: 读取/更新操作时发生Dynamodb ConditionalCheckFailedException

下一篇: 在gradle.properties文件中声明数组/散列表