六狼论坛

 找回密码
 立即注册

QQ登录

只需一步,快速开始

新浪微博账号登陆

只需一步,快速开始

搜索
查看: 52|回复: 0

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

[复制链接]

升级  74%

9

主题

9

主题

9

主题

童生

Rank: 1

积分
37
 楼主| 发表于 2013-1-27 05:08:28 | 显示全部楼层 |阅读模式
假设我们有这样的代码:
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属性和作为参数传递给闭包来实现的。
您需要登录后才可以回帖 登录 | 立即注册 新浪微博账号登陆

本版积分规则

快速回复 返回顶部 返回列表