在groovy中,我扩展了LinkedHashMap并重载了getAt,PutAt运算符:
class Container extends LinkedHashMap<String, Object> {
def get(String id){ 'my '+id }
def put(String id, Object value){ super.put(id, 'val:'+value ) }
def getAt(String id){ get(id) }
def putAt(String id, Object value){ put(id, value) }
}
如果我直接调用方法或使用[]表示法,在groovy上使用我的类似乎很好用:
def c = new Container()
c['x'] = 'y'
assert c.get('x') == c['x']
但使用字段表示法访问地图不会返回正确的值:
assert c['x']!=c.x
我如何重载'.field'表示法来调用我的重载方法作为[]表示法?
P.S。我试过'propertyMissing'并没有成功。
答案 0 :(得分:2)
适用于getProperty
和setProperty
:
class Container extends LinkedHashMap<String, Object> {
def getProperty(String id) { 'get prop '+id }
void setProperty(String id, Object value){ super.put(id, 'val:'+value ) }
}
def c = new Container()
c['x'] = 'y'
assert c.y == 'get prop y'
assert c['x'] == c.x
答案 1 :(得分:0)
您应该适当地覆盖get()
方法:
def get(String id) {
super.get(id)
}
然后,一切正常:
class Container extends LinkedHashMap<String, Object> {
def get(String id) {
super.get(id)
}
def put(String id, Object value) {
super.put(id, 'val:'+value )
}
def getAt(String id) {
get(id)
}
def putAt(String id, Object value) {
put(id, value)
}
}
def c = new Container()
c['x'] = 'y'
assert c.get('x') == c['x']
assert c['x'] == c.x