access groovy map by dynamic key

牧云@^-^@ 提交于 2019-12-10 23:34:33

问题


I want a construct a groovy map with dynamic key as below, and want to get the value by dynamic key. But I am not able to access it, it returns null for the same key.

class AmazonPackage {
    public static String WEIGHT = "WEIGHT"
}

class PackageTests {

   @Test
   void "map should return value by dynamic key" () {
       def map = [ ("${AmazonPackage.WEIGHT}") : 100, "id": "package001"]

       assert map['id'] == "package001"

       //assert map[("${AmazonPackage.WEIGHT}")] == 100
       //assert map."${AmazonPackage.WEIGHT}" == 100

       assert 2 == map.keySet().size()
       assert map."WEIGHT" == 100 //fails
    }

    @Test
    void "map should return value by simple key" () {
        def map = ["w" : 100]
        assert map."w" == 100
    }

}

Failure I get is,

Assertion failed: 

assert map."WEIGHT" == 100
       |   |        |
       |   null     false
       [WEIGHT:100, id:package001]

回答1:


Unfortunately, the map key you are storing is a GString, not a String. This means the map is not considering those keys equal.

If you want to access your map with String values, you should store the key as a string:

def map = [ ("${AmazonPackage.WEIGHT}".toString()) : 100, "id": "package001"]
assert map."WEIGHT" == 100



回答2:


First of all if you want to fetch value from a map using "." operator then you directly provide the key like map.key to fetch value for key 'key' from map.

Secondly, as the class for "${AmazonPackage.WEIGHT}" is GStringImpl and not a plain String object, you cann't fetch its value using simple "." operator, instead you should use get(). Also this get will return result only if you provide the key as a GStringImpl and not plain String object: map.get("${AmazonPackage.WEIGHT}")




回答3:


I would recommend setting the map like so:

def map = [ (AmazonPackage.WEIGHT) : 100, "id": "package001"]

And doing your assertion like so:

assert map[AmazonPackage.WEIGHT] == 100



来源:https://stackoverflow.com/questions/35283215/access-groovy-map-by-dynamic-key

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!