Gradle buildConfigField 使用Hashma

2020-09-08  本文已影响0人  星辰大海TT

buildConfigField可以在gradle脚本中定义我们需要的变量,然后在代码中引用。

官方文档上buildConfigField 定义的格式是这样的:


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

我们可以很方便的定义基础类型,如type为Long String int boolean等基础类型,但是我们能不能定义数组,Hashmap,ArrayList等java常用的数据结构呢?

答案是可以的,我们可以定义任何我们想要的对象。

如我们可以定义字符串数组:


      buildConfigField "String[]", "ARRAY",
     "{" +
      "\"test1\"," +
        "\"test2\"," +
        "\"test3\"" +
        "}"

和Map类型:


    buildConfigField "java.util.Map<String, String>", "NAME_MAP",

                "new java.util.HashMap<String, " +

                "String>() {{ put(\"name\", \"John\"); put(\"name1\",  \"daniel\"); put(\"name2\", " +

                "\"anna\"); }}"

测试下,build.gradle中定义如下:

  //string 类型需要引号包括
        buildConfigField "String", "CHANNEL_KEY", "\"APP_CHANNEL\""
        buildConfigField "String[]", "ARRAY",
                "{" +
                        "\"test1\"," +
                        "\"test2\"," +
                        "\"test3\"" +
                        "}"
        buildConfigField "java.util.Map<String, String>", "NAME_MAP",
                "new java.util.HashMap<String, " +
                        "String>() {{ put(\"name\", \"John\"); put(\"name1\",  \"daniel\"); put(\"name2\", " +
                        "\"anna\"); }}"
        buildConfigField "java.util.ArrayList<String>", "NAME_ARRAYLIST",
                "new java.util.ArrayList<String>() {{ add(\"John\"); add( \"daniel\"); add(\"anna\"); }}"

build后生成的BuildConfig文件如下:

/**

- Automatically generated file. DO NOT MODIFY
  */
  package com.wxkly.aroutertest;

public final class BuildConfig {

  // Fields from default config.
  public static final String[] ARRAY = {"test1","test2","test3"};
  public static final String CHANNEL_KEY = "APP_CHANNEL";
  public static final java.util.ArrayList<String> NAME_ARRAYLIST = new java.util.ArrayList<String>() {{ add("John"); add( "daniel"); add("anna"); }};
  public static final java.util.Map<String, String> NAME_MAP = new java.util.HashMap<String, String>() {{ put("name", "John"); put("name1",  "daniel"); put("name2", "anna"); }};
  public static final boolean isBuild = false;
  public static final int size = 0;
}

可以看到生成了相应的java.util.ArrayListjava.util.Map

这里需要注意的是buildConfig文件中无法使用import引入相关的包名,所有我们在定义buildConfigField的时候需要使用类名加package路径如:java.util.Map

上一篇下一篇

猜你喜欢

热点阅读