Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: Migrated to Confluence 5.3

Using ExpandoMetaClass to add behaviour

Groovy 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? Every java.lang.Class is supplied with a special "metaClass" property that will give you a reference to an ExpandoMetaClass instance.

For example to obtain the ExpandoMetaClass of the java.lang.String class you use:

Code Block
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.

Note

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:

Children Display
excerpttrue