简体   繁体   中英

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 )

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)

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM