美文网首页
Groovy闭包

Groovy闭包

作者: 涅小黑 | 来源:发表于2020-04-22 01:07 被阅读0次
  • 闭包定义与调用
    //默认参数 it
    Closure c = {
        it+5
    }

    //显式命名参数,此时就没有it
    Closure d = { k ->
        k+5
    }
    
    //闭包的调用
    c.call(7)

*动态闭包

    def f(Closure closure){
        //根据闭包的参数的个数执行不同的逻辑
        if (closure.maximumNumberOfParameters == 2){}
        else{}   
        
        for (param in closure.parameterTypes){
            param.name //参数的类型
        }
    }

    //不同参个数的闭包调用的内部逻辑是不一样的
    f{ param1 -> }
    f{ param1,param2 -> }
  • this、owner、delegate
    闭包里面有3个重要的对象,把它们弄清楚了,才能对一些代码有全面的理解
    this:创建闭包的对象(上下文)
    owner:如果闭包在另外一个闭包中创建,owner指向另一个的闭包,否则指向this
    delegate:默认指向owner,但可以设置为其他对象

闭包里面的属性和方法调用与三个对象有密切的关系,闭包中有个resolveStrategy,默认值为0

    public static final int OWNER_FIRST = 0;
    public static final int DELEGATE_FIRST = 1;
    public static final int OWNER_ONLY = 2;
    public static final int DELEGATE_ONLY = 3;

属性或者方法调用的查找顺序
OWNER_FIRST:
own -> this -> delegate

DELEGATE_FIRST
delegate->own -> this

class Hello {

//    def a = "hello a"
    def innerC

    def c = {
//        def a = "closure a"

        innerC = {
            println(a)
        }

        delegate = new Delegate()

        //修改闭包的delegate
        innerC.delegate = delegate
        //设置闭包的代理策略
        innerC.setResolveStrategy(Closure.OWNER_FIRST)

        innerC.call()
    }

    def f(){
        c.call()
    }

}

class Delegate {
    def a = "delegate a"
}

相关文章

  • 详解 groovy 的闭包(上)

    groovy 的闭包特点 在 groovy 中的闭包。groovy 中的闭包是一个开放的匿名代码块,可以接受参数,...

  • Groovy 闭包

    本文介绍了Groovy闭包的有关内容。闭包可以说是Groovy中最重要的功能了。如果没有闭包,那么Groovy除了...

  • Groovy语法简介

    Groovy简单语法: Groovy中的闭包:

  • 二、Groovy语法(二):闭包

    Groovy闭包 1、Groovy中闭包基础 1.1 闭包的概念闭包是被包装成对象的代码块,可以通过一个变量引用到...

  • 《Groovy极简教程》第9章 Groovy闭包(Closure

    《Groovy极简教程》第9章 Groovy闭包(Closures)

  • Groovy 闭包

    好久没动笔(键盘)了,发现自己变懒了。但是在实际的工作过程中,总是责怪自己没有动笔把自己之前的遇到的问题记录下来,...

  • Groovy 闭包

    闭包 闭包是一段可执行的代码块,类似于方法也可以传递参数;可在闭包中访问属性值,也就是说可以修改闭包作用域中的所有...

  • Groovy闭包

    闭包定义与调用 *动态闭包 this、owner、delegate闭包里面有3个重要的对象,把它们弄清楚了,才能对...

  • Groovy语法基础三

    上接Groovy语法基础二 六、闭包 闭包,英文叫Closure,是Groovy中非常重要的一个数据类型或者说一...

  • Groovy Closure(闭包)

    1. 语法 1.1. 定义一个闭包 闭包是Groovy中非常重要的一个数据类型或者说一种概念。闭包是一种数据类型,...

网友评论

      本文标题:Groovy闭包

      本文链接:https://www.haomeiwen.com/subject/ysqwbhtx.html