[英]Map returns null when getting value based on key name
I have a very strange problem regarding getting values from LinkedHashMap in Grovvy when running in Jenkins pipeline. 在Jenkins管道中运行时,关于从Grovvy中的LinkedHashMap获取值有一个非常奇怪的问题。
I have a map like this: map = ['key1': 'param1']
我有一个这样的地图: map = ['key1': 'param1']
Now I want to get a value of key1, so I call map.get('key1')
or map['key1']
. 现在,我想获取key1的值,因此我调用map.get('key1')
或map['key1']
。 Surprisingly both of these return null
. 令人惊讶的是,这两个都返回null
。
When I try to call map.keySet()
, it returns key1
. 当我尝试调用map.keySet()
,它返回key1
。 And most interestingly, when I call map.get(map.keySet()[0])
it return param1
as expected. 最有趣的是,当我调用map.get(map.keySet()[0])
它会按预期返回param1
。
So how is it possible that the direct map.get('key1')
doesn't work? 那么直接map.get('key1')
怎么可能不起作用?
UPDATE: 更新:
After some investigation, I have found out that the key1
is not a String but org.codehaus.groovy.runtime.GStringImpl
. 经过一番调查,我发现key1
不是String,而是org.codehaus.groovy.runtime.GStringImpl
。 Does anybody have any idea why it was casted to this class and not String? 有人知道为什么将其强制转换为此类而不是String吗?
This is how the initial map is created: 初始地图的创建方法如下:
result = ["${key}": value]
Following code does work. 以下代码确实有效。
map = ['key1': 'param1']
assert 'param1' == map['key1']
After the update in Question 更新后的问题
The key was actually not a String. 关键实际上不是字符串。 toString()
will give to you string as String
, that can be used as key toString()
将为您提供字符串String
,可以用作键
GStrings (groovy.lang.GString) which are also called interpolated strings in other programming languages. GString(groovy.lang.GString)在其他编程语言中也称为内插字符串。 "${key}"
is a GString, but "${key}".toString()
is a String. "${key}"
是一个GString,但是"${key}".toString()
是一个String。 More detail at here 在这里更多细节
Following approach can resolve your issue 以下方法可以解决您的问题
def key = 'key1'
def a = "${key}" // or a = "${key}".toString()
def result = [:]
result[a] = 'param1'
println result.key1 // or result['key1']
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.