In groovy, is there a way to check if an object has a given method?

groovy

Solution

Use `respondsTo`

class Foo {
   String prop
   def bar() { "bar" }
   def bar(String name) { "bar $name" }
}

def f = new Foo()

// Does f have a no-arg bar method
if (f.metaClass.respondsTo(f, "bar")) {
   // do stuff
}
// Does f have a bar method that takes a String param
if (f.metaClass.respondsTo(f, "bar", String)) {
   // do stuff
}

Problem

Assuming that I have an object `someObj` of indeterminate type, I'd like to do something like: ``` def value = someObj.someMethod() ``` Where there's no guarantee that 'someObj' implements the `someMethod()` method, and if it doesn't, just return `null`. Is there anything like that in Groovy, or do I need to wrap that in an if-statement with an `instanceof` check?

Original source

Related problems