加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

groovy 接口

发布时间:2020-12-14 16:51:37 所属栏目:大数据 来源:网络整理
导读:1.? [代码] 用闭包来实现接口(1)????? 跳至?[1]?[2]?[3]? [全屏预览] view source print ? 1 //如果接口只有一个方法,可以通过闭包,用下面的方式来实现: 2 ? 3 ? // a readable puts chars into a CharBuffer and returns the count of chars added 4 def

1.?[代码]用闭包来实现接口(1)?????跳至?[1]?[2]?[3]?[全屏预览]

view source
print ?
1 //如果接口只有一个方法,可以通过闭包,用下面的方式来实现:
2 ?
3 ?// a readable puts chars into a CharBuffer and returns the count of chars added
4
def?readable = { it.put("12 34".reverse());?5?}?as?Readable
5 ?
6 // the Scanner constructor can take a Readable
7 s =?new?Scanner(readable)
8 assert?s.nextInt() ==?43
2.?[代码]用闭包来实现接口(方法2)?????
01 你也可以用闭包来实现方法数多于一个的接口。当调用接口中的任何方法时,这个闭包都会被调用一次。
02 由于所有的方法都要复用这个闭包的参数表,因此典型的做法是用一个对象数组来作为底座容器。
03 这种做法也可以用于任何Groovy的闭包,并且会把所有的参数都放在这个数组中。例如:
04 05 ?interface?X
06 {?void?f();?g(int?n);?h(String s,?n); }
07 08 x = {Object[] args ->?println?"method called with $args"X
09 x.f()
10 x.g(1)
11 x.h("hello",2)
3.?[代码]用Map 来实现接口(方法1)?????
impl = [
??i:?10
hasNext: { impl.i >?0?},
next: { impl.i-- },monospace!important; font-size:10pt!important; min-height:inherit!important">]
iter = impl?Iterator
while?( iter.hasNext() )
??println?iter.next()
//上面的例子只是一个故意设计的示例,但却展示了这个概念。
//你可以仅仅实现那些真正被调用的方法,但如果你调用了一个Map 中未实现的方法时,将会抛出异常NullPointerException ,如:
12 13 14 15 16 x = [ f: {"f called"} ]?17 18 //x.g()??? // NPE here

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

相关内容
推荐文章
站长推荐
热点阅读