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:
String.metaClass.swapCase = {-> def sb = new StringBuffer() delegate.each { sb << (Character.isUpperCase(it as char) ? Character.toLowerCase(it as char) : Character.toUpperCase(it as char)) } sb.toString() }
This adds a method called swapCase to the String class.
| By default ExpandoMetaClass doesn't do inheritance. To enable this you must call ExpandoMetaClass.enableGlobally() before your app starts such as in the main method or servlet bootstrap |
Further Reading:
- ExpandoMetaClass - Borrowing Methods — Borrowing methods from other classes
- ExpandoMetaClass - Constructors — Adding or overriding constructors
- ExpandoMetaClass - Dynamic Method Names — Dynamically creating method names
- ExpandoMetaClass - GroovyObject Methods — Overriding invokeMethod, getProperty and setProperty
- ExpandoMetaClass - Interfaces — Adding methods on interfaces
- ExpandoMetaClass - Methods — Adding or overriding instance methods
- ExpandoMetaClass - Overriding static invokeMethod — Overriding invokeMethod for static methods
- ExpandoMetaClass - Properties — Adding or overriding properties
- ExpandoMetaClass - Runtime Discovery — Overriding invokeMethod for static methods
- ExpandoMetaClass - Static Methods — Adding or overriding static methods






