从groovy配置文件动态分配值

时间:2020-12-12 01:38:21

As I am reading values from a file in my Groovy code, I want to assign these values to the equivalent properties in my object as i am iterating through the map values!

当我从Groovy代码中的文件中读取值时,我想将这些值分配给对象中的等效属性,因为我正在遍历地图值!

code:

new ConfigSlurper().parse(new File(configManager.config.myFile.filepath)
                   .toURI().toURL()).each { k,v -> 
    if (k == 'something') {
        v.each {
            myObject.$it =v.$it 
            // so here i want this dynamic assignment to occur 
        }
     }
}

1 个解决方案

#1


You code there would already work like this, if you would use the form:

如果您使用表单,您的代码就会像这样工作:

myObject."$it.key" = it.value

Here is a slightly more protective version:

这是一个稍微保护的版本:

class MyObject {
    Long x,y
}

def obj = new MyObject()

def cfg = new ConfigSlurper().parse('''\
a { 
    x = 42
    y = 666
}
b {
    x = 93
    y = 23
}''')

cfg.b.findAll{ obj.hasProperty(it.key) }.each{
    obj.setProperty(it.key,it.value)
}

assert obj.x==93 && obj.y==23

#1


You code there would already work like this, if you would use the form:

如果您使用表单,您的代码就会像这样工作:

myObject."$it.key" = it.value

Here is a slightly more protective version:

这是一个稍微保护的版本:

class MyObject {
    Long x,y
}

def obj = new MyObject()

def cfg = new ConfigSlurper().parse('''\
a { 
    x = 42
    y = 666
}
b {
    x = 93
    y = 23
}''')

cfg.b.findAll{ obj.hasProperty(it.key) }.each{
    obj.setProperty(it.key,it.value)
}

assert obj.x==93 && obj.y==23