Groovy用字段扩展了hashmap [英] Groovy extended hashmap with a field

查看:257
本文介绍了Groovy用字段扩展了hashmap的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这不起作用。

This doesn't work. Shouldn't it?

class WeirdBean extends HashMap {
  public String inner = "set within"
  def getInner() { return this.inner }
  def getOuter() { return this.outer }
}

def o = WeirdBean.newInstance()
o.outer = "set without"
println o.getOuter()  // set without
println o.outer       // set without
assert o.outer == o.getOuter() // Pass

println o.getInner()  // set within
println o.inner       // null, even though public
assert o.inner == o.getInner() // Fail, o.inner is null


推荐答案

code> Map :: get 的优先级高于 object.field object.property 。由于类内部的字段访问没有通过getter,所以这是有效的:

Seems like Map::get has higher precedence than object.field or object.property. Since a field access inside a class doesn't go through the getter, this works:

class WeirdBean extends HashMap {
  public String inner = "set within"
  def getInner() { return this.inner }

  def getProperty(String property) { 
    (property == 'inner') ? inner : super.get(property) 
  }

  def getOuter() { return this.outer }
}

def o = WeirdBean.newInstance()
o.outer = "set without"
println o.getOuter()  // set without
println o.outer       // set without
assert o.outer == o.getOuter() // Pass

println o.getInner()  // set within
println o.inner       // null, even though public
assert o.inner == o.getInner() // Fail, o.inner is null

这篇关于Groovy用字段扩展了hashmap的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆