【发布时间】:2015-05-16 12:54:58
【问题描述】:
我理解we cannot access Map properties the same way we access them in other classes,因为能够在 groovy 中获取带有点符号的映射键。
现在,对于实现 java.util.Map 的类,有没有办法仍然受益于使用 propertyMissing 的 expando 元类?
这是我正在尝试的:
LinkedHashMap.metaClass.methodMissing = { method, args ->
println "Invoking ${method}"
"Invoking ${method}"
}
LinkedHashMap.metaClass.propertyMissing = { method, args ->
println "Accessing ${method}"
"Accessing ${method}"
}
def foo = [:]
assert "Invoking bar" == foo.bar() // this works fine
assert "Accessing bar" == foo.bar // this doesn't work, for obvious reasons, but I'd like to be able to do that...
我一直在尝试通过自定义 DelegatingMetaClasses 但没有成功...
【问题讨论】:
-
你能举一个有用的例子吗?举个例子,也许我们可以想办法做到这一点
-
访问地图中不存在的键时,我想尝试获取从缺少的键名派生的另一个键...
-
例如,对于任何地图,如果键 foo_bar 不存在,我想查找 fooBar
标签: groovy