質問

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
役に立ちましたか?

解決

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

他のヒント

Expression o.inner returns key from HashMap. There's no such key inner so null is returned, while inside getInner() method value of this.inner field is returned (which is set to "set without". That's why.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top