Dark theme | Light theme

October 17, 2009

Groovy Goodness: Check If Method or Property is Available

In Groovy we can easily see if a method or property is available for an object. We can use the respondsTo() and hasProperty() methods to see if the method or property can be invoked or accessed. We can not check for methods or properties which are added by overriding the methodMissing()/propertyMissing() or invokeMethod()/getProperty() methods.

class Simple {
    String language
    def whatDoYouSpeak() {  
    def say(String text) {
        "You say $text in $language"

def s = new Simple(language: 'Groovy')

assert s.metaClass.respondsTo(s, 'whatDoYouSpeak')
assert Simple.metaClass.respondsTo(s, 'say')
assert s.metaClass.respondsTo(s, 'say', String)
assert !s.metaClass.respondsTo(s, 'say', Integer)  // No say(Integer) method.
assert Simple.metaClass.respondsTo(s, 'toString')  // Method in parent object.

assert s.metaClass.hasProperty(s, 'language')
assert Simple.metaClass.respondsTo(s, 'getLanguage')  // Get/set methods are generated.
assert s.metaClass.respondsTo(s, 'setLanguage')