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 6 Next »

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.

Icon

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:

  1. Adding or overriding instance methods
  2. Adding methods to an instance
  3. Adding or overriding static methods
  4. Adding or overriding properties
  5. Adding or overriding constructors
  6. Adding methods on interfaces
  7. Dynamically creating method names
  8. Overriding invokeMethod, getProperty and setProperty
  9. Overriding invokeMethod for static methods
  10. Evaluating MetaClass instances at runtime
  11. Borrowing methods from other classes
  • No labels