Gradle buildConfigField: syntax for arrays and maps?

The android gradle documentation talks about buildConfigField:

void buildConfigField (String type, String name, String value)

Adds a new field to the generated BuildConfig class. The field is generated as: type name = value;

This means that each of them must have valid Java content. If the type is a string, then the value must include quotation marks.

Can't find syntax information for buildConfigField values ​​for arrays, Arraylist or HashMap? Since they are compiled into java code, usually everything should be possible.

Does anyone have examples or documentation?

+13
source share
4 answers

app.gradle

        buildConfigField "String[]", "URL_ARRAY",
        "{" +
        "\"http:someurl\"," +
        "\"http:someurl\"," +
        "\"http:someurl\"" +
        "}"

        buildConfigField "java.util.Map<String, String>", "NAME_MAP", 
                 "new java.util.HashMap<String, " +
                 "String>() {{ put(\"name\", \"John\"); put(\"name1\",  \"John\"); put(\"name2\", " +
                "\"John\"); }}"

:

HashMap<String, String> name = (HashMap<String, String>) BuildConfig.NAME_MAP;
+25

, buildConfig , .

- + gradle.properties ( Gradle 2.13 ):

gradle.properties:


nonNullStringArray=new String[]{ \n\
    \"foo\",\n\
    \"bar\"\n}

build.gradle:

buildConfigField "String[]", "nonNullStringArray", (project.findProperty("nonNullStringArray") ?: "new String[]{}")

buildConfigField "String[]", "nullableStringArray", (project.findProperty("nullableStringArray") ?: "null")


+2

, . 1:1 Java, , Java Gradle .

HashSet:


buildConfigField "java.util.Set<String>", "MY_SET", "new java.util.HashSet<String>() {{ add(\"a\"); }};"


0

Gradle :

ext {
    // Environments list
    apiUrl = [
            prod         : "https://website.com",
            preprod      : "https://preprod.website.com"
    ]
}

Android Gradle:

private static String getApiUrlHashMapAsString(apiUrlMap) {
    def hashMap = "new java.util.HashMap<String, String>()" + "{" + "{ "
    apiUrlMap.each { k, v -> hashMap += "put(\"${k}\"," + "\"${v}\"" + ");" }
    return hashMap + "}" + "}"
}

android {
    defaultConfig {
         buildConfigField "java.util.Map<String, String>", "API_URLS", getApiUrlHashMapAsString(apiUrl)
    }
}

:

BuildConfig.API_URLS
0

Source: https://habr.com/ru/post/1669237/


All Articles