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

本文介绍了Groovy语言中with方法的使用方式及其内部实现原理。通过示例代码展示了如何利用with方法简化对象方法调用,并深入探讨了DefaultGroovyMethods中的实现细节。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

假设我们有这样的代码:

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属性和作为参数传递给闭包来实现的。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值