Wednesday, July 16, 2008

A Groovy way to generate delegate methods

To generate delegate methods When working with Java in Eclipse, you simply go to Source->Generate Delegate Methods and voila. For example, when implementing a decorator:



public Class MyDecorator extends SuperClass {
private SuperClass decorated;

void someMethod() {
this.decorated.someMethod();
}
void otherMethod() {
this.decorated.otherMethod();
}
void andAnotherMethod() {
this.decorated.andAnotherMethod();
}
void anotherMoreMethod() {
this.decorated.anotherMoreMethod();
}
}

This can be a really tedious task if there's many methods and you aren't working with an IDE. Well, here's another reason to love Groovy. Simply use missingMethod to invoke the corresponding decorated class method when a method call fails on the decorator class:



class MyDecorator {
SuperClass decorated

def methodMissing(String name, args) {
decorated.invokeMethod(name,args)
}
}

Now, if you for example call myDecorator.otherMethod() the call will fail cause otherMethod is
not declared in MyDecorator, then a call to methodMissing is triggered, invoking the corresponding method in the decorated object

No comments: