groovy闭包基本用法

来源:互联网 发布:大数据行业 职位 编辑:程序博客网 时间:2024/06/10 03:35
//闭包 基本用法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)//闭包可以有默认值 再赋值 直接赋给jdef 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 delegateclass 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()
原创粉丝点击