[英]How to write java class methods that can accept groovy closures
Here's what I want to do: 这就是我想要做的事情:
I have a class called RowCollection
which contains a collection of Row
objects, with a method named edit
, which is supposed to accept as a parameter another method (or closure) which operates on a Row
object. 我有一个名为
RowCollection
的类,它包含一个Row
对象的集合,其中有一个名为edit
的方法,它应该接受另一个对Row
对象进行操作的方法(或闭包)作为参数。
A groovy script will be using an object of this class in the following way: 一个groovy脚本将以下列方式使用此类的对象:
rc.edit({ it.setTitle('hello world') }); // it is a "Row" object
My questions: 我的问题:
RowCollection#edit
look like? RowCollection#edit
的签名会是什么样的? As an alternative, if you make RowCollection
implement Iterable<Row>
and provide a suitable iterator()
method then the standard Groovy-JDK magic applied to all classes will enable 作为替代方案,如果您使
RowCollection
实现Iterable<Row>
并提供合适的iterator()
方法,那么应用于所有类的标准Groovy-JDK魔法将启用
rc.each { it.title = "hello world" }
and you get all the other iterator
-backed GDK methods for free in the same way, including collect
, findAll
, inject
, any
, every
and grep
. 并以相同的方式免费获得所有其他
iterator
支持的GDK方法,包括collect
, findAll
, inject
, any
, every
和grep
。
Okay - a little bit of digging, and here it is: 好的 - 一点点挖掘,这里是:
class RowCollection {
private List<Row> rows;
// ...
public void edit(Closure c) {
for(Row r : rows) {
c.call(r);
}
}
// ...
}
the class Closure is in groovy.lang
package. Closure类在
groovy.lang
包中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.