[英]Get Method from Groovy method closure
groovy中的.&
運算符在閉包中轉換方法。 在Java中使用反射Method對象,可以獲取方法名稱,參數名稱和類型。 有沒有辦法從閉包中獲取所有方法反射信息? 到目前為止,我只能獲取參數類型(通過closure.parameterTypes
)
從方法創建閉包時,實際上並沒有鏈接java.lang.Method
而只是鏈接了一個名稱:如果您具有名稱相同但參數不同的其他方法,那么它將起作用。
當您使用參數調用閉包時,groovy嘗試查找適合參數的最佳方法(與Groovy一樣)。
因此,您不能從閉包中獲取Method
,但可以得到名稱:
def closure = instance.@myMethod
assert "myMethod" == closure.method
然后,您可以從owner
類中找到所有可能的方法:
def methods = closure.owner.metaClass.respondsTo(closure.owner, closure.method)
不是直接從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)
。&運算符返回MethodClosure ,該方法維護owner
屬性中對實例的引用。 因此,您可以從那里轉到Class
,最后到Method
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.