简体   繁体   English

从Groovy方法关闭获取方法

[英]Get Method from Groovy method closure

In groovy the .& operator converts a method in a closure. groovy中的.&运算符在闭包中转换方法。 In Java using the reflection Method object, one can get the method name, parameters names and types. 在Java中使用反射Method对象,可以获取方法名称,参数名称和类型。 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 ) 到目前为止,我只能获取参数类型(通过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. 从方法创建闭包时,实际上并没有链接java.lang.Method而只是链接了一个名称:如果您具有名称相同但参数不同的其他方法,那么它将起作用。

When you call the closure with parameters, groovy try to lookup the best method which fit the parameters (as usual in Groovy). 当您使用参数调用闭包时,groovy尝试查找适合参数的最佳方法(与Groovy一样)。

So, you can't get a Method from a closure, but you can get the name : 因此,您不能从闭包中获取Method ,但可以得到名称:

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

You can then find all possible methods from the owner class: 然后,您可以从owner类中找到所有可能的方法:

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

Not directly from the Closure , but you can get the Method from the Closure : 不是直接从Closure中获取,而是可以 Closure获取Method

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. 。&运算符返回MethodClosure ,该方法维护owner属性中对实例的引用。 So you can go from there, to the Class , and then finally to the Method . 因此,您可以从那里转到Class ,最后到Method

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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