通过动态密钥访问groovy地图 [英] access groovy map by dynamic key

查看:112
本文介绍了通过动态密钥访问groovy地图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要一个带有动态密钥的常规图,如下所示,并且想通过动态密钥获取值。但是我无法访问它,它为相同的键返回null。

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]


推荐答案

不幸的是,你存储的map key是一个 GString ,而不是 String 。这意味着地图不会考虑这些关键字相同。

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

这篇关于通过动态密钥访问groovy地图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆