我正在编写代码,当我处理XML和Maps时,我注意到Groovy中有一些奇怪的行为.我想到了它,无法弄清楚为什么会这样,应该这样.
我用3个例子编写了示例代码. map1&的重要区别map3仅在以下部分:
地图1:
map1 << ["${it.name()}":it.value()]
MAP3:
map3["${it.name()}"]=it.value()
这是完整的代码,您可以将其复制粘贴到Groovy控制台:
def xml = '<xml><head>headHere</head><body>bodyHere</body></xml>' Map map1 = [:] def node = new XmlParser().parseText(xml) node.each { map1 << ["${it.name()}": it.value()] } println map1 println map1["head"] println ">>>>>>>>>>>>>>>>>>>>>>" Map map2 = [:] map2 << ["head":"headHere"] map2 << ["body":"bodyHere"] println map2 println map2["head"] println "<<<<<<<<<<<<<<<<<<<<<<" def xml2 = '<xml><head>headHere</head><body>bodyHere</body></xml>' Map map3 = [:] def node2 = new XmlParser().parseText(xml2) node2.each { map3["${it.name()}"]=it.value() } println map3 println map3["head"]
我得到的结果如下:
[head:[headHere],body:[bodyHere]] null [head:headHere,body:bodyHere] headHere [head:[headHere],body:[bodyHere]] [headHere]
即使map1和map3看起来相同,map [“head”]的结果也完全不同,首先给出null,然后给出实际结果.我不明白为什么会这样.我花了一些时间在它上面仍然没有得到它.我使用.getProperty()来获取类的信息,但它看起来一样,并且在地图和对象里面感觉相同.我尝试了更多的东西,没有什么能让我知道发生了什么.我甚至尝试过不同的操作系统(Win XP,Mac OS),但仍然没有.
我不再有任何想法,请一个人解释奇怪的行为,为什么会发生这种情况以及map<<<< [key:object]和map [key] = object? 谢谢.
解决方法
可能有用的一件事是,不要使用GStrings作为密钥. Groovy支持将对象直接用作键,将它们包装在括号中.
从the manual开始:
Map keys are strings by default: [a:1] is equivalent to [“a”:1]. But if you really want a variable to become the key,you have to wrap it between parentheses: [(a):1].
完全工作的例子:
def xml = '<xml><head>headHere</head><body>bodyHere</body></xml>' Map map1 = [:] def node = new XmlParser().parseText(xml) node.each { map1 << [ (it.name()): it.value() ] } println map1 println map1["head"] println ">>>>>>>>>>>>>>>>>>>>>>" Map map2 = [:] map2 << ["head":"headHere"] map2 << ["body":"bodyHere"] println map2 println map2["head"] println "<<<<<<<<<<<<<<<<<<<<<<" def xml2 = '<xml><head>headHere</head><body>bodyHere</body></xml>' Map map3 = [:] def node2 = new XmlParser().parseText(xml2) node2.each { map3[it.name()] = it.value() } println map3 println map3["head"]
输出是:
[head:[headHere],body:[bodyHere]] [headHere] >>>>>>>>>>>>>>>>>>>>>> [head:headHere,body:bodyHere] headHere <<<<<<<<<<<<<<<<<<<<<< [head:[headHere],body:[bodyHere]] [headHere]