13

At runtime I'm grabbing a list of method names on a class, and I want to invoke these methods. I understand how to get the first part done from here: http://docs.codehaus.org/display/GROOVY/JN3535-Reflection

GroovyObject.methods.each{ println it.name }

What I can't seem to find information on is how to then invoke a method once I've grabbed its name.

What I want is to get here:

GroovyObject.methods.each{ GroovyObject.invokeMethod( it.name, argList) }

I can't seem to find the correct syntax. The above seems to assume I've overloaded the default invokeMethod for the GroovyObject class, which is NOT the direction I want to go.

avgvstvs
  • 6,196
  • 6
  • 43
  • 74

2 Answers2

23

Once you get a MetaMethod object from the metaclass, you can call invoke on it. For example:

class MyClass {
    def myField = 'foo'
    def myMethod(myArg) { println "$myField $myArg" }
}
test = new MyClass()
test.metaClass.methods.each { method ->
    if (method.name == 'myMethod') {
        method.invoke(test, 'bar')
    }
}

Alternatively, you can use the name directly:

methodName = 'myMethod'
test."$methodName"('bar')
ataylor
  • 64,891
  • 24
  • 161
  • 189
  • 1
    Is there a way to check if the method exists without iterating over `metaClass.methods`? – Alexander Suraphel Oct 30 '14 at 14:32
  • 2
    @AlexanderSuraphel The [`respondsTo()`](http://docs.groovy-lang.org/latest/html/groovy-jdk/java/lang/Object.html#respondsTo(java.lang.String)) method will tell you if the method exists. Example: `if (test.respondsTo(methodName)) { ... }` – ataylor Feb 27 '15 at 16:40
20

Groovy allows for dynamic method invocation as well as dynamic arguments using the spread operator:

def dynamicArgs = [1,2]
def groovy = new GroovyObject()
GroovyObject.methods.each{ 
     groovy."$it.name"(staticArg, *dynamicArgs)
}

Reference here

Question answered here.

rboy
  • 2,018
  • 1
  • 23
  • 35
avgvstvs
  • 6,196
  • 6
  • 43
  • 74
  • 1
    While this may theoretically answer the question, [it would be preferable](http://meta.stackexchange.com/q/8259) to include the essential parts of the answer here, and provide the link for reference. – Bill the Lizard Jan 03 '12 at 18:05
  • The provided link is dead. Does this link similar? http://www.groovy-lang.org/metaprogramming.html#_dynamic_method_names – chrish Sep 11 '15 at 17:05
  • I updated the link to point to an archived version of the original, now dead link. Happy metaprogramming! – avgvstvs Jan 06 '16 at 12:48