`
JohnnyJian
  • 浏览: 104330 次
  • 性别: Icon_minigender_1
  • 来自: 上海
社区版块
存档分类
最新评论

Groovy学习笔记——使用with方法减少代码

阅读更多
假设我们有这样的代码:
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属性和作为参数传递给闭包来实现的。
分享到:
评论
1 楼 RayChase 2008-10-27  
恩 有收获~

相关推荐

Global site tag (gtag.js) - Google Analytics