1

这是我的 groovy 文件的内容:

def KEY = "a"

Properties myProp = new Properties()
myProp[KEY] = "b"
assert(myProp[KEY] == myProp.getProperty(KEY))

Properties results = new Properties(myProp)
assert(results[KEY] == results.getProperty(KEY))

我希望两个断言都能通过,但只有第一个断言通过,第二个断言失败。

对此的任何解释都非常感谢。谢谢!

4

1 回答 1

1

因此,当文档说“创建一个空的属性列表”时,它就是这样做的:

println(results)
>>> [:]

看看有什么getProperty作用:

在此属性列表中搜索具有指定键的属性。如果在该属性列表中未找到该键,则递归地检查默认属性列表及其默认值。如果未找到该属性,则该方法返回 null。

得出的结论是[]( getAt) 不搜索默认属性列表。

我们可以通过这个来看看 Groovy 是如何实现的getAt

public static <K,V> V getAt(Map<K,V> self, K key) {
    return self.get(key);
}

所以它正在调用底层Hashtableget方法,它对默认属性列表一无所知——默认值是 的一部分Properties,而不是Hashtable

println(results.getProperty(KEY))
>>> b
println(results.getAt("a"))
>>> null
println(results.get("a"))
>>> null

这是“正确”的行为吗?可能不会——也许 a是合适的Properties.getAt

于 2012-06-02T01:05:52.600 回答