groovy闭包基本用法

//闭包 基本用法
def closure_my = {
    println 'groovy'
}

//调用闭包
closure_my.call()
closure_my()

//闭包能默认接收一个参数
closure_my('hello closure')

//闭包接收多个参数
def closure1 = {
    i,j ->
    println 'groovy'
    println i + " " + j
}
closure1(1,2)

//闭包可以有默认值 再赋值 直接赋给j
def closure2 = {
    i = 'xx',j->
        println i + "--" + j
}
closure2("aa")

//柯里化闭包 动态给闭包添加默认参数 返回新的闭包
// curry 从左到右赋值  ncurry 从第几个开始赋值  rcurry从右到左赋值
// 注意: 这个方法得到的新闭包不可以再给已经赋值默认值得参数赋值了
def closure3 = {
    i,j->
        println i + "--" + j
}
def closure4 = closure3.rcurry("aa")
closure4.call("bb")

//对一个对象调用() 表示调用这个对象上的call方法
//建一个接口
interface Action{
    void call()
}
//新建一个方法
def func(aa){
    aa()
}
//执行方法
func(new Action(){

    @Override
    void call() {
        println "call"
    }
})
//新建类 通过类的对象()调用call方法
class Action1{
    def call(){
        println "类内部call"
    }
}
new Action1()



//closure成员
def closure5 = {
    int i,char j ->
}
println closure5.parameterTypes // 得到参数类型  输出:[int, char]
println closure5.maximumNumberOfParameters //最大参数个数 输出:2

//闭包的 this owner delegate
class TestClosure{
    def closure6 = {
        def closure7 = {
            println "this is: " + this
            println "owner is: " + owner
            println "delegate is: " + delegate
        }
        closure7()
    }
}
new TestClosure().closure6()
/**
 * 输出
 * this is: TestClosure@48e4374
 * owner is: TestClosure$_closure1@3e2e18f2
 * delegate is: TestClosure$_closure1@3e2e18f2cb
 * this      定义它的时候 所在的类的this 静态闭包当中为 class
 * owner     定义它的时候 所在类的对象
 * delegate  默认是owner
 */

//通过代理 获取代理中的方法
class TestFunc{
    def funcc(){
        println 'TestFunc : funcc'
    }
}
def closure8 = {
    funcc()
}
def funcc(){
    println "Closure : funcc"
}
closure8.delegate = new TestFunc()
closure8()
//代理策略 当代理和类本身都有同一个方法时  选择哪个优先
//默认是 OWNER_FIRST 默认是自己优先
//
closure8.resolveStrategy = Closure.DELEGATE_FIRST // 代理优先
closure8()
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值