- 闭包定义与调用
//默认参数 it
Closure c = {
it+5
}
//显式命名参数,此时就没有it
Closure d = { k ->
k+5
}
//闭包的调用
c.call(7)
*动态闭包
def f(Closure closure){
//根据闭包的参数的个数执行不同的逻辑
if (closure.maximumNumberOfParameters == 2){}
else{}
for (param in closure.parameterTypes){
param.name //参数的类型
}
}
//不同参个数的闭包调用的内部逻辑是不一样的
f{ param1 -> }
f{ param1,param2 -> }
- this、owner、delegate
闭包里面有3个重要的对象,把它们弄清楚了,才能对一些代码有全面的理解
this:创建闭包的对象(上下文)
owner:如果闭包在另外一个闭包中创建,owner指向另一个的闭包,否则指向this
delegate:默认指向owner,但可以设置为其他对象
闭包里面的属性和方法调用与三个对象有密切的关系,闭包中有个resolveStrategy,默认值为0
public static final int OWNER_FIRST = 0;
public static final int DELEGATE_FIRST = 1;
public static final int OWNER_ONLY = 2;
public static final int DELEGATE_ONLY = 3;
属性或者方法调用的查找顺序
OWNER_FIRST:
own -> this -> delegate
DELEGATE_FIRST
delegate->own -> this
class Hello {
// def a = "hello a"
def innerC
def c = {
// def a = "closure a"
innerC = {
println(a)
}
delegate = new Delegate()
//修改闭包的delegate
innerC.delegate = delegate
//设置闭包的代理策略
innerC.setResolveStrategy(Closure.OWNER_FIRST)
innerC.call()
}
def f(){
c.call()
}
}
class Delegate {
def a = "delegate a"
}