Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I dynamically invoke methods in Groovy?

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.

like image 663
avgvstvs Avatar asked Jan 03 '12 17:01

avgvstvs


1 Answers

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')
like image 113
ataylor Avatar answered Oct 16 '22 10:10

ataylor