Code Groovy

Code Groovy

Small Gem: @Delegate annotation

While looking through some source code of the open source library groovy-wslite, I came across an annotation I had not seen before - @Delegate. This annotation adds all public instance methods of the annotated field to the present class. In the example from groovy-wslite, the field soapResponse is annotated with @Delegate:

class SoapFaultException {
  @Delegate
  SoapResponse soapResponse
}

This means that all of SoapResponse's public instance methods will be available as methods on all instances of SoapFaultException, and you can do the following:

try {
  // do something
} catch (SoapFaultException e) {
  log.info(e.getFault())
}

Note that getFault isn't defined in SoapFaultException. But it's defined in SoapResponse and since @Delegate is used, we can use it as if it's defined in SoapFaultException. Behind the scenes, the above code translates to:

try {
  // do something
} catch (SoapFaultException e) {
  log.info(e.soapResponse.getFault())
}

See more info about @Delegate here.

 
Share this