简体   繁体   English

如何编写可以接受groovy闭包的java类方法

[英]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: 我的问题:

  1. what will the signature of RowCollection#edit look like? RowCollection#edit的签名会是什么样的?
  2. what can its implementation look like? 它的实现是什么样的?

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方法,包括collectfindAllinjectanyeverygrep

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM