Adding a functionality to the existing Java/Groovy classes
How many times have you dreamed of adding a new method to a final class or to a class that you don't even have sources for? With Groovy, you are given the ability to do so. That's all possible thanks to Groovy's extension methods. The original class stays untouched and Groovy takes care of catching extended method calls.
In fact, we have already seen examples of this feature in some of the recipes in Chapter 2, Using Groovy Ecosystem, for example, the Using Java classes from Groovy and Embedding Groovy into Java recipes, and we'll see more in coming recipes of this book. Groovy extends many of the standard JDK classes (for example, java.io.File
, java.lang.String
, java.util.Collection
, and so on). It's one of the many cool Groovy features that makes working with some old Java APIs a pleasant business.
In this recipe, we are going to cover the mechanism of creating an extension module to an existing Java class, and then using that class...