Search code examples
groovyevaluate

Is any error in my code in using evaluate in groovy?


I'm setting value to a nested Map, the keys are all exist, here is my code:

def map = [a1:[a2:[a3:'a123']], b1:[b2:[b3_1:'b234', b3_2:'b345']], d1:'d1']
def name2 = "b1:::b2:::b3_1"
def data = "test"
def separator = ":::"

def names = name2.split(separator)

setValue(map, names, data)

def setValue(def map, def keys, def data) {
    tmpMap = map
    String str = 'map' 
    for (i = 0; i < keys.size(); i++) {
        str = str.concat('.'+ keys[i])
    }
    str = str.concat(" = '" + data + "'")

    evaluate(str)
}

the str content will be "map.b1.b2.b3_1 = 'test'" I can manually run it and the map content is changed, but when I use evaluate, there has error of "java.lang.NullPointerException: Cannot get property 'b2' on null object", would you please tell me what's wrong with the code, thanks a lot.


Solution

  • recurse approach:

    def setValue(def map, List keys, def data) {
        return keys.size()>1 ? 
            setValue(map[keys[0]],keys.subList(1,keys.size()),data) : 
                map.put(keys[0],data)
    }