通过读取.properties文件收集的buildConfigField

时间:2018-08-19 11:45:16

标签: android gradle android-gradle

Gradle buildConfigField: Syntax for arrays & maps?帖子提示生成Dictionary的{​​{1}},Set<T>CollectionHashTable<T>

我想知道可以加载buildConfigField文件并生成其集合作为.properties变量。

dev.properties

BuildConfig

app.gradle

Variable1 = 'some'
Variable2 = 'value'

预期结果1

通过在Java代码中访问ext { // Read properties file Properties devProperty = new Properties() def devPropertyFile = file(getRootDir().getPath() + File.separator + 'developer.properties') try { devProperty.load(new FileInputStream(devPropertyFile)) } catch (FileNotFoundException e) { devProperty = null System.out.println('devProperty is null') } // Read property field names as a String set Set<String> devSet = devProperty?.stringPropertyNames() } android { ... defaultConfig { // Below trial gives error buildConfigField 'java.util.Set<String>', 'PropertyNames', project.devSet } } 可获得BuildConfig.devSet值。

预期结果2

最好通过以下应用程序代码访问["Variable1, Variable2"]本身;

Properties devProperty

1 个答案:

答案 0 :(得分:0)

我创建了gradle函数以生成texted-inline-function

example.properties假定数据类型为<String, Boolean>对。

example.properties

example1 = true
example2 = false

渐变功能

android {
    defaultConfig {
        // read file from project root folder
        buildConfigField 'java.util.Hashtable<String, Boolean>', 'PropertyPairs', makePropertyHashTable(getRootDir().getPath() + File.separator + 'developer.properties')
    }
}

def makePropertyHashTable(filename) {
    def devProperties = new Properties()
    try {
        devProperties.load(new FileInputStream(file(filename)))
    } catch (FileNotFoundException e) {
        devProperties = null
        System.out.println('devProperties is null')
    }

    // result example: new Hashtable<String, Boolean>(){{ put(true, "a"); }};
    def prefix = 'new java.util.Hashtable<String, Boolean>(){{ '
    def suffix = '}}'
    def value = ''
    if (devProperties != null) {
        for (d in devProperties) {
                value += String.format('put("%s",%s); ', d.key, d.value)
            }
        }
    }
    return String.format('%s%s%s', prefix, value, suffix)
}

应用程序代码用法

if (BuildConfig.PropertyPairs.getOrDefault("example1", false) == true) {
    // do something
}