There are many situations where you might find that it would be useful if a class not under your control had additional methods that you define. In order to enable this capabilities, Groovy implements a feature borrowed from Objective-C , called Categories. There are a few categories that are included in the system for adding functionality to classes that make them more usable within the Groovy environment.
The first category allows you to treat DOM objects as arrays and maps so that you can use them in conjunction with the Groovy path expression language and treat them like JavaBeans. Here is an example from the tests of using the DOMCategory:
As you can see here we are treating DOM objects just as if they were JavaBeans and are accessing them with GPath. The ServletCategory is similarly used when we want to treat the attributes of Servlet API objects as if they were properties since they don't follow the typical conventions for JavaBeans or Maps either. In the GroovyServlet that lets you use scripts as servlets we call GroovyCategorySupport from Java in order to make it possible to use property accessors against the request:
This allows users to access things like Session attributes and request Attributes by name instead of through the API within their Groovy servlet scripts. For example, without this you would have to do:
With this you can say it more tersely as:
In order to create your own Categories and extend classes yourself you'll need to understand what the "use" keyword expects to be defined within the class you pass to it. To add a method to a class T, simply define a new class with a static method that whose first parameter is of type T. Here is a simple example from the tests:
This code will print out the string "test". This facility is extremely powerful and essentially lets you change the way any class in the system works when it is called from Groovy code. Note though that you can't add methods to classes, pass them to Java code, and expect the Java code to be able to call them. Since most people use statically typed Java with little reflection I doubt this case would come up much anyway.
Here is an example of using this as an end user in order to add methods to Apple's own NSDictionary and NSArray class in order to manipulate their Cocoa objects as if they were native Groovy objects:
Notice how we can even create Category classes in Groovy code. They essentially look just like built-in ones within
DefaultGroovyMethods. Define them by creating a static method that takes the type you want to extend, then the additional parameters that the new method will take.