Richie Richie - 11 days ago 5
Groovy Question

Re-write java anonymous class in groovy style closure?

I am a Java programmer trying to learn groovy. Closures are a bit confusing for me at the moment.

Could I have some help to understand how I can use a closure to replace the abstract code I have below. I'm thinking a function defined as a variable or something like that however I can't crack it yet.

//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)
}


thanks

Answer

There's not much you can do here (w/o knowing other details), but this:

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
    }
Comments