在groovy样式关闭中重写java匿名类?

时间:2016-11-23 04:24:00

标签: groovy

我是一名试图学习groovy的Java程序员。目前关闭对我来说有点混乱。

我可以帮助理解如何使用闭包替换下面的抽象代码。我正在考虑将一个函数定义为一个变量或类似的东西,但是我还不能破解它。

//MY ABSTRACT CLASS
public abstract class AbstractResource {

    protected StreamingOutput activityStreamingOutput(serviceResponse){
        return new StreamingOutput() {
                    @Override
                    public void write(OutputStream os) throws IOException,
                    WebApplicationException {
                        def writer = new BufferedWriter(new OutputStreamWriter(os));
                        writer.write(serviceResponse);
                        writer.flush();
                    }
                }
    }
}

// MY CHILD CLASS
class MaintanenceResourceImpl extends AbstractResource{

    public void doSomething(Reader reader) throws Exception {
          // I'D LIKE TO DO SOMETHING GROOVYISH HERE
          def StreamingOutput = activityStreamingOutput(serviceResponse)
    }

感谢

1 个答案:

答案 0 :(得分:1)

你在这里做的并不多(不知道其他细节),但是这个:

abstract class AbstractResource {

    Closure activityStreamingOutput(serviceResponse){
        { OutputStream os ->
            os.withWriter{ it << serviceResponse }
        }
    }
}

class MaintanenceResourceImpl extends AbstractResource {

    void doSomething(Reader reader) throws Exception {
          activityStreamingOutput(serviceResponse).call someOutputStream
    }