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

Accepted answer
Score: 74

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
}

0

Score: 6

Just implement methodMissing in your class:

class Foo {
   def methodMissing(String name, args) { return null; }
}

And 4 then, every time you try to invoke a method 3 that doesn't exist, you will get a null 2 value.

def foo = new Foo();
assert foo.someMethod(), null

For more information, take a look 1 here: http://groovy.codehaus.org/Using+methodMissing+and+propertyMissing

Score: 4

You should be able to do something like:

SomeObj.metaClass.getMetaMethod("someMethod")

Or 2 you can fall back to the good old Java reflection 1 API.

Score: 4

You can achieve this by using getMetaMethod together 1 with the safe navigation operator ?.:

def str = "foo"
def num = 42

def methodName = "length"
def args = [] as Object[]

assert 3 == str.metaClass.getMetaMethod(methodName, args)?.invoke(str, args);
assert null == num.metaClass.getMetaMethod(methodName, args)?.invoke(num, args);
Score: 2

if class :

   MyClass.metaClass.methods*.name.any{it=='myMethod'}//true if exist

if object :

myObj.class.metaClass.methods*.name.any{it=='myMethod'}//true if exist

0

More Related questions