Gradle buildConfigField: Syntax for arrays & maps?

Deadly 提交于 2019-11-30 17:36:57

For array

app.gradle

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

For Map

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

Access in code:

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

IMHO the reason for using buildConfig fields is to keep important data out of the code - like environment variables.

another example - static arrays + gradle.properties (requires Gradle 2.13 or above):

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")


Fahim

Ok I got it now. The parameters are translated 1:1 in java, this means in fact you need to code java inside gradle and escape properly.

For HashSet:


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


Another example here

Gradle file with environments :

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

Gradle Android file :

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)
    }
}

In your code :

BuildConfig.API_URLS
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!