groovy学习8-接口

 

代码
   
     
/* *
* @author <a href="mailto:[email protected]">张挺</a>
* @since 2010-4-6 11:12:33
*
*/
// Implement interfaces with a closure

// a readable puts chars into a CharBuffer and returns the count of chars added,这个5是返回值-_-b
def readable = { it.put( " 12 34 " .reverse()); 5 } as Readable

// the Scanner constructor can take a Readable
def s = new Scanner(readable)
assert s.nextInt()
== 43

// 使用闭包实现多方法接口,闭包将会被每个接口调用,参数需要匹配
interface X {
void f();

void g( int n);

void h(String s, int n);
}

x
= {Object[] args -> println " method called with $args " } as X
x.f()
x.g(
1 )
x.h(
" hello " , 2 )

// Implement interfaces with a map

impl
= [
i:
10 ,
hasNext: { impl.i
> 0 },
next: { impl.i
-- },
]
iter
= impl as Iterator
while (iter.hasNext())
println iter.next()

// You only need to implement those methods that are actually called,
//
but if a method is called that doesn't exist in the map a NullPointerException is thrown.
//
你只需要实现需要被调用的方法,但是一旦使用到没有实现的方法,就会报NPE
x = [f: {println " f called " }] as X
x.f()
// x.g() // NPE here

// Be careful that you don't accidentally define the map with { }
//
不要用{}来定义map,接口里的每个方法都会调用{}闭包
x = { f: {println " f called " } } as X
x.f()
x.g(
1 )

// class.forname得到的是interface的实例,而不是一种类型,可以用astype来取得接口类型
def loggerInterface = Class.forName( ' my.LoggerInterface ' )
def logger
= [
log: {Object[] params
-> println " LOG: ${params[0]} " ; if (params.length > 1 ) params[ 1 ].printStackTrace() },
close: { println
" logger.close called " }
].asType(loggerInterface)

 

 

 

你可能感兴趣的:(groovy)