【Groovy】闭包 Closure ( 闭包调用 与 call 方法关联 | 接口中定义 call() 方法 | 类中定义 call() 方法 | 代码示例 )

文章目录

总结

一、接口中定义 call() 方法

二、类中定义 call() 方法

三、完整代码示例

总结


在 实例对象后使用 " () " 括号符号 , 表示调用该实例对象的 " call() " 方法 ;






一、接口中定义 call() 方法


定义 Action 接口 , 在该接口中 , 创建 void call() 抽象方法 ;


/**
 * 创建接口
 * 接口中定义 call 方法
 * 调用上述 接收 闭包作为参数的 fun 函数时
 * 传入该 Action 匿名内部类
 */
interface Action {
    void call()
}


创建上述 Action 方法的匿名内部类 , 并 使用 () 执行上述匿名内部类对象 , 会 自动调用 Action 匿名内部类的 call 方法 ;


// 在 Action 对象后使用 () 执行方法相当于调用 call 方法
new Action(){
    @Override
    void call() {
        println "Closure 3"
    }
}()


执行上述代码 , 会打印


Closure 3


内容 ;



同时上述匿名内部类 , 可以当做闭包 , 传递给


/**
 * 定义一个方法 , 接收闭包作为参数 , 在方法中执行闭包内容
 * @param closure
 * @return
 */
def fun(closure) {
    closure()
}


函数 ; 向 fun 函数中 , 传入 Action 匿名内部类 , 此时执行该函数时 , 执行闭包内容 , 会自动调用 Action 匿名内部类的 call 方法 ;


// 向 fun 函数中 , 传入 Action 匿名内部类
// 此时执行该函数时 , 执行闭包内容 , 会自动调用 Action 匿名内部类的 call 方法
fun (new Action(){
    @Override
    void call() {
        println "Closure 3"
    }
})


上述 fun 函数的执行结果 :


Closure 4






二、类中定义 call() 方法


在普通的 Groovy 类中 , 定义 call() 方法 ;


// 定义一个有 call 方法的类
class Action2 {
    def call() {
        println "Closure 5"
    }
}


在该类实例对象后 使用 () , 会自动执行该类的 call 方法 ;


// 在该类实例对象后使用 () , 会自动执行该类的 call 方法
new Action2()()


执行结果为 :


Closure 5






三、完整代码示例


完整代码示例 :


/**
 * 定义一个方法 , 接收闭包作为参数 , 在方法中执行闭包内容
 * @param closure
 * @return
 */
def fun(closure) {
    closure()
}
/**
 * 创建接口
 * 接口中定义 call 方法
 * 调用上述 接收 闭包作为参数的 fun 函数时
 * 传入该 Action 匿名内部类
 */
interface Action {
    void call()
}
// 将 闭包 当做 参数 传递到函数中
fun ({
    println "Closure 1"
})
// 闭包是函数的最后一个参数 , 可以 省略括号 , 将闭包写在函数后面
fun {
    println "Closure 2"
}
// 在 Action 对象后使用 () 执行方法相当于调用 call 方法
new Action(){
    @Override
    void call() {
        println "Closure 3"
    }
}()
// 向 fun 函数中 , 传入 Action 匿名内部类
// 此时执行该函数时 , 执行闭包内容 , 会自动调用 Action 匿名内部类的 call 方法
fun (new Action(){
    @Override
    void call() {
        println "Closure 4"
    }
})
// 定义一个有 call 方法的类
class Action2 {
    def call() {
        println "Closure 5"
    }
}
// 在该类实例对象后使用 () , 会自动执行该类的 call 方法
new Action2()()



执行结果 :


Closure 1
Closure 2
Closure 3
Closure 4
Closure 5

【Groovy】闭包 Closure ( 闭包调用 与 call 方法关联 | 接口中定义 call() 方法 | 类中定义 call() 方法 | 代码示例 )

上一篇:Selenium自动化测试框架入门整理


下一篇:Jenkins持续集成项目搭建与实践——基于Python Selenium自动化测试(*风格)