假设我们有这样的代码:
我们可以通过Object上的with方法省去test对象的限定:
我们可以从Groovy的源代码中看到这是如何实现的,在org.codehaus.groovy.runtime.DefaultGroovyMethods中:
可以看出这是通过把对象赋值给闭包的delegate属性和作为参数传递给闭包来实现的。
class Test {
def fun1() { println 'a' }
def fun2() { println 'b' }
def fun3() { println 'c' }
}
def test = new Test()
test.fun1()
test.fun2()
test.fun3()
我们可以通过Object上的with方法省去test对象的限定:
test.with {
it.fun1()
it.fun2()
it.fun3()
}
// 或者连it也省去
test.with {
fun1()
fun2()
fun3()
}
我们可以从Groovy的源代码中看到这是如何实现的,在org.codehaus.groovy.runtime.DefaultGroovyMethods中:
public static Object with(Object self, Closure closure) {
final Closure clonedClosure = (Closure) closure.clone();
clonedClosure.setDelegate(self);
return clonedClosure.call(self);
}
可以看出这是通过把对象赋值给闭包的delegate属性和作为参数传递给闭包来实现的。