检索 Groovy 闭包/方法参数列表 [英] Retrieve Groovy Closure/Method parameters list
问题描述
我们如何通过参数数组以javascript风格动态检索groovy中的闭包/方法的参数列表
How do we retrieve the list of parameters of a closure/method in groovy dynamically, javascript style through the arguments array
例如说我想以这种方式记录一条消息
say for example that i want to log a message this way
def closure = {name,id ->
log.debug "Executing method with params name:${} id:${id}"
}
或
void method (String name,String id) {
log.debug "Executing method with params name:${} id:${id}"
}
我读过一次关于引用闭包参数列表的方法,但我不记得它并查看了 Closure 仅显示 getParametersType() 方法.至于方法,有一种方法可以调用一个方法作为一个闭包,然后我可以检索方法参数
I read once about a way to reference the list of parameters of a closure, but i have no recollection of that and looking at the groovy API for Closure reveals only getParametersType() method. As for the method, there is a way to call a method as a closure and then i can retrieve the method parameters
肯
推荐答案
你不会喜欢它(我希望做研究和回答不是我的坏事),但是:
You won't like it (and I hope it's not my bad to do research and to answer), however:
没有 API 可以访问在 Groovy Closure
或 Java Method
中声明的参数列表.
There is no API to access the list of parameters declared in a Groovy Closure
or in a Java Method
.
我还查看了相关类型,包括(对于 Groovy)MetaClass
、子类型和 org.codehaus.groovy.reflection
包中的类型, 和(对于 Java)java.lang.reflect
包中的类型.
I've also looked at related types, including (for Groovy) MetaClass
, and sub-types, and types in the org.codehaus.groovy.reflection
package, and (for Java) types in the java.lang.reflect
package.
此外,我进行了广泛的 Google 搜索以追踪外星人.;-)
Furthermore, I did an extensive Google search to trace extraterrestrials. ;-)
如果我们需要一个可变长度的闭包或方法参数列表,我们可以使用 Object[]
数组、List
或 varargs代码>作为参数:
If we need a variable-length list of closure or method arguments, we can use an Object[]
array, a List
, or varargs
as parameters:
def closure = { id, Object... args ->
println id
args.each { println it }
}
closure.call(1, "foo", "bar")
好吧,这就是限制和选项!
Well, that's the limitations and options!
这篇关于检索 Groovy 闭包/方法参数列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!