简体   繁体   English

如何从groovy覆盖java方法

[英]How to override a java method from groovy

I have a groovy class that has the ability to write its output to a StringWriter - (via a setStringWriter method). 我有一个groovy类,它能够将其输出写入StringWriter - (通过setStringWriter方法)。

In java I would use the following code: 在java中我会使用以下代码:

filter.setStringWriter(new StringWriter(){
   @Override
   public void write(String string){
       // do something with the string
   }
}); 

For Groovy I'm told to use a closure, I've tried the following with no luck: 对于Groovy,我被告知要使用一个闭包,我已经尝试了以下但没有运气:

def s =  {String line -> print line} as StringWriter
filter.setStringWriter(s)

or 要么

filter.setStringWriter{String line -> print line}

How do I go about doing this, or is it even possible? 我该怎么做呢,或者甚至可能吗?

The following link gives a clue, although it only mentions interfaces. 以下链接给出了一个线索,虽然它只提到了接口。

The following works with Groovy 1.6.1: 以下适用于Groovy 1.6.1:

def s =  [ write: { String line -> print line} ] as StringWriter
filter.setStringWriter(s)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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