Skip to end of metadata
Go to start of metadata

You are viewing an old version of this page. View the current version.

Compare with Current View Page History

« Previous Version 4 Next »

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. We call these 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. 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 looks just like 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.

  • No labels