문제

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