2gether
2gether

Reputation: 55

hasProperty returns null

I am trying to identify if the Groovy (actually Grails domain) class has a property with the hasProperty method. It always returns null. getProperty founds this. What is the difference between those two methods?

Groovy has the javadoc for the hasProperty , but it's not clear at all.

Returns true of the implementing MetaClass has a property of the given name

Note that this method will only return true for realised properties and does not take into account implementation of getProperty or propertyMissing

Is this groovy meta protocol bug?

Groovy 2.0.7 from grails 2.2.1 .

Thanks!

Upvotes: 3

Views: 2740

Answers (1)

Will
Will

Reputation: 14529

hasProperty identifies class properties binded to the metaclass of an object, whereas getProperty can be pretty arbitrary: you can write a method to return whatever you want. How can hasProperty get into that? Executing getProperty? Seems a bit weird to me.

You can override hasProperty so it consider whatever logic is in getProperty:

class Person {
  Map otherProperties = [:]
  def getProperty(String property) {
    otherProperties[property]
  }

  void setProperty(String prop, value) { 
    otherProperties[prop] = value 
  }

  boolean hasProperty(String property) { 
    otherProperties.containsKey(property) 
  }
}

p = new Person()
p.name = "John"
p.age = 40

assert p.hasProperty('name')
assert p.hasProperty('age')
assert !p.hasProperty('dob')

Upvotes: 1

Related Questions