Antonio
Antonio

Reputation: 181

Get Method from Groovy method closure

In groovy the .& operator converts a method in a closure. In Java using the reflection Method object, one can get the method name, parameters names and types. Is there a way to get all the method reflection information from the closure? I'm only able to get the parameter types so far (via closure.parameterTypes)

Upvotes: 2

Views: 2799

Answers (2)

Jérémie B
Jérémie B

Reputation: 11032

When you create a closure from a Method, you are not really linking a java.lang.Method but only a name: If you have differents methods with the same name, but differents parameters, it will work.

When you call the closure with parameters, groovy try to lookup the best method which fit the parameters (as usual in Groovy).

So, you can't get a Method from a closure, but you can get the name :

def closure = instance.@myMethod
assert "myMethod" == closure.method

You can then find all possible methods from the owner class:

def methods = closure.owner.metaClass.respondsTo(closure.owner, closure.method)

Upvotes: 2

Emmanuel Rosa
Emmanuel Rosa

Reputation: 9895

Not directly from the Closure, but you can get the Method from the Closure:

import java.lang.reflect.Method

class Person {
    def firstName
    def lastName

    def getFullName() {
        "$firstName $lastName"
    }
}

Person person = new Person(firstName: 'John', lastName: 'Doe')
Closure closure = person.&getFullName
Method method = closure.owner.class.getMethod('getFullName')

assert person.fullName == closure()
assert person.fullName == method.invoke(person)

The .& operator returns a MethodClosure, which maintains a reference to the instance in the owner property. So you can go from there, to the Class, and then finally to the Method.

Upvotes: 2

Related Questions