Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

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.

...

For example given the Java class java.lang.String to obtain its ExpandoMetaClass you can 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()
}

...

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