我是靠谱客的博主 干净蚂蚁,这篇文章主要介绍groovy闭包基本用法,现在分享给大家,希望可以做个参考。

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
//闭包 基本用法 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) //闭包可以有默认值 再赋值 直接赋给j def 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 delegate class 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()

最后

以上就是干净蚂蚁最近收集整理的关于groovy闭包基本用法的全部内容,更多相关groovy闭包基本用法内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(50)

评论列表共有 0 条评论

立即
投稿
返回
顶部