Sparkle’s Workshop

Archive for April 14th, 2005

Closures with CollectionUtils

Posted on April 14, 2005 - Filed Under Uncategorized

http://raibledesigns.com/page/rd?anchor=closures_with_collectionutils

List list = new ArrayList();

CollectionUtils.forAllDo(list, new Closure() {
public void execute(Object obj) {
// execute something for each item obj
}
});

看了这个代码片断,大家应该能写出forAllDo()和Closure的代码
不过这里跟groovy closure还有点差别,比groovy closure多了一层{}
其实groovy closure说白了就是函数指针,在c/c++里也有的东西
当然groovy把语法弄得更简单
java里是用只有一个method的interface的匿名子类来模拟函数指针
最明显的例子是thread里经常使用的Runnable接口
这么做没看出比函数指针好多少,只是java里没有“指针”,没有办法不这么处理
其实groovy没有办法脱离java没有“指针”这个问题
所以groovy closure也是用一个method的interface匿名子类来处理的
所以难免会表现出block的特性
就是之前大牛门讨论的return/break/continue在groovy closure里的事情

Read More..>>