我对 groovy 比较陌生,并且在 gradle 构建的上下文中使用它。因此,如果有一个简单的开箱即用的解决方案,请不要太苛刻。
基本上我正在尝试完成 Return Nested Key in Groovy 的相反任务。也就是说,我从System.properties
读取了一些 key 。 map 例如 user.home
以及相应的值,如 C:\User\dpr
。现在我想创建一个反射(reflect)此结构的 map ,以便在 groovy.text.SimpleTemplateEngine
中使用它。作为绑定(bind):
[user : [home : 'C:\Users\dpr']]
键可以定义任意深度的层次结构。例如java.vm.specification.vendor=Oracle Corporation
应该变成:
[java : [vm : [spec : [vendor : 'Oracle Corporation']]]]
此外,还有具有相同父级的属性,例如 user.name=dpr
和user.country=US
:
[
user: [
name: 'dpr',
country: 'US'
]
]
编辑:同时 ConfigSlurper
确实不错,但创建嵌套映射有点过于防御性,因为它会在某个键的最小深度处停止嵌套。
我目前最终使用了这个
def bindings = [:]
System.properties.sort().each {
def map = bindings
def split = it.key.split("\\.")
for (int i = 0; i < split.length; i++) {
def part = split[i];
// There is already a property value with the same parent
if (!(map instanceof Map)) {
println "Skipping property ${it.key}"
break;
}
if (!map.containsKey(part)) {
map[part] = [:]
}
if (i == split.length - 1) {
map[part] = it.value
} else {
map = map[part]
}
}
map = it.value
}
使用此解决方案,属性 file.encoding.pkg
, java.vendor.url
和java.vendor.url.bug
被丢弃,这不太好,但我可以应付。
但是上面的代码不是很groovyish。
最佳答案
您可以使用 ConfigSlurper :
def conf = new ConfigSlurper().parse(System.properties)
println conf.java.specification.version
关于dictionary - 从 groovy 中的键创建嵌套映射,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38396695/