Domanda

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
È stato utile?

Soluzione

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

Altri suggerimenti

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.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top