文章目录
- 线程中的闭包调用
- 自定义闭包重写`doCall`
- 查找并调用闭包成员
- 闭包中的形参
- 扩展闭包的实参控制
线程中的闭包调用
package com.juan.groovyclass MyThread extends Thread {// 闭包成员变量Closure closureMyThread(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 messageprintln 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不满足条件