闭包是 Closure 对象 , Closure 类中有很多成员 , 以及封装的函数 , 下面是 Closure 类的继承结构 ;
/**
* 在 Groovy 中代表任何闭包对象 .
* <p>
* Groovy允许以简短的形式调用闭包实例。例如:
* <pre>
* def a = 1
* def c = { a }
* assert c() == 1
* </pre>
* 为了能够以这种方式在您自己的子类中使用闭包,
* 您需要提供一个带有您想要的任何签名的doCall方法。
* 这确保了{@link#getMaximumNumberOfParameters()}
* 和{@link#getParameterTypes()}在
* 没有任何额外代码的情况下也可以工作。
* 如果没有提供doCall方法,则必须以长形式使用闭包,如
* <pre>
* def a = 1
* def c = {a}
* assert c.call() == 1
* </pre>
*
* @author <a href="mailto:james@coredevelopers.net">James Strachan</a>
* @author <a href="mailto:tug@wilson.co.uk">John Wilson</a>
* @author <a href="mailto:blackdrag@gmx.org">Jochen Theodorou</a>
* @author Graeme Rocher
* @author Paul King
*/
public abstract class Closure<V>
extends GroovyObjectSupport
implements Cloneable, Runnable, GroovyCallable<V>, Serializable {
}
在 闭包类 Closure 中 , 有如下
个成员 :
protected Class[] parameterTypes;
protected int maximumNumberOfParameters;
Class[] parameterTypes
是参数类型 , int maximumNumberOfParameters
是最大所需参数个数 , 当调用闭包时 , 不知道向闭包中传递什么类型的参数时 , 不知道传入多少个参数时 , 此时可以使用 上述
个成员 ;
如下代码 , 定义一个闭包 :
// 定义闭包
// 该闭包接收 2 个参数
def closure = {
int a, String b ->
}
如果使用上述 closure 闭包时 , 不知道该闭包接收什么类型的参数 , 和参数个数 , 可以使用 println 打印闭包参数 ;
打印参数类型 : 上述
个参数 , 打印出来的结果是 [int, class java.lang.String] ;
// 打印参数类型
println closure.parameterTypes
打印参数个数 :
// 打印参数个数
println closure.maximumNumberOfParameters
完整代码示例 :
// 定义闭包
// 该闭包接收 2 个参数
def closure = {
int a, String b ->
}
// 打印参数类型
println closure.parameterTypes
// 打印参数个数
println closure.maximumNumberOfParameters
执行结果 :
[int, class java.lang.String]
2