groovy闭包语法详解(二)

线程中的闭包调用

package com.juan.groovy

class MyThread extends Thread {
    // 闭包成员变量
    Closure closure

    MyThread(Closure c) {
        this.closure = c
        // 启动线程,运行闭包
        this.start()
    }
    // 线程运行方法
    public void run() {
        // 这种写法跟js很像,不为null则执行
        if (closure) {
            closure()
        }
    }
}

// 下面两个线程会交替打印
new MyThread({
    (1..9).each {
        sleep(10 * it)
        println it
    }
})

new MyThread({
    ["a", "b", "c", "d"].each {
        sleep(100)
        println it
    }
})

自定义闭包重写doCall

class MyClosure extends Closure{
    MyClosure(owner) {
        super(owner)
    }

    MyClosure(owner, thisObject) {
        super(owner, thisObject)
    }
    // 该方法在调用闭包时会隐式调用,注意接收的参数类型,如果不加限制,则调用时可传入任何类型
    Object doCall(String message) {
        println message
        println owner // 当前所在类
        println this // 闭包类
        return null
    }
}

MyClosure c = new MyClosure(this)
c 'hello'
c 123 // 报错

查找并调用闭包成员

// 定义我的姑娘
class MyGirl {
    // 公有闭包成员变量
    public lough = {
        println 'Hahaha...'
    }
}

void callMyGirlAction(Class clz, String action) {
    // 通过反射获取闭包成员变量进行调用
    def myGirl = clz.getDeclaredConstructor().newInstance()
    myGirl.getClass().getDeclaredField(action).get(myGirl).call()
}

callMyGirlAction(MyGirl.class, 'lough')

闭包中的形参

// 以下的闭包中接收各种参数形式(最多一个参数)
def defaultParams = { println it }
def dynamicParams = { arg -> println arg }
def intParams = { int arg -> println arg }
def stringParams = { String arg -> println arg }
def noParams = { -> }

// 调用
defaultParams 'hello'
defaultParams() // 可传空
dynamicParams 123
dynamicParams 'hi'
intParams 123
stringParams '123'
noParams()
noParams 1 // 不可传参,报错

默认参数和不接收参数的区别

默认参数it,在调用时不传参则显示null;而空箭头的形式,在调用时不能传参数,否则抛异常

扩展闭包的实参控制

// 用一个数组来接收参数
class Closure1 extends Closure{

    Closure1(owner) {
        super(owner)
    }

    def doCall(Object[] params ) {
        println params
    }
}
closure1 = new Closure1(this)
closure1 'hello' // [hello]
closure1 'hello', 1, 0.1 // [hello, 1, 0.1]


// 可接收一个任意类型的参数
class Closure2 extends Closure{

    Closure2(owner) {
        super(owner)
    }
    
    def doCall(arg) {
        println arg
    }
}
closure2 = new Closure2(this)
closure2 'hello'
closure2 1
closure2 'hello', 1, 0.1 // 报错


// 接收一个指定类型的参数
class Closure3 extends Closure{
    Closure3(owner) {
        super(owner)
    }
    def doCall(String arg) {}
}
closure3 = new Closure3(this)
closure3 'hello'
closure3 1 // 报错


// 通过闭包来检查一个数组是否都是数字
def arr = [1, 2, 3, 'a']
Closure intParams = { int arg -> }
arr.each intParams // 报错,检测到字符串a不满足条件
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Java小卷

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值