Using ExpandoMetaClass to add behaviour
Groovy 1.1 includes a special MetaClass called an ExpandoMetaClass that allows you to dynamically add methods, constructors, properties and static methods using a neat closure syntax.
How does it work? Well every java.lang.Class is supplied with a special "metaClass" property that when used will give you a reference to an ExpandoMetaClass instance.
For example given the Java class java.lang.String to obtain its ExpandoMetaClass you can use:
This adds a method called
swapCase to the String class.
- Adding or overriding instance methods
- Adding methods to an instance
- Adding or overriding static methods
- Adding or overriding properties
- Adding or overriding constructors
- Adding methods on interfaces
- Dynamically creating method names
- Overriding invokeMethod, getProperty and setProperty
- Overriding invokeMethod for static methods
- Evaluating MetaClass instances at runtime
- Borrowing methods from other classes