Versions Compared


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


Adding or overriding instance methods

ExpandoMetaClass - Adding & Overriding instance methods

Once you have an ExpandoMetaClass to add new methods to it is trivial:

Code Block
class Book {
   String title

Book.metaClass.titleInUpperCase << {-> title.toUpperCase() }

def b = new Book(title:"The Stand")

assert "THE STAND" == b.titleInUpperCase()

Note that in this case the left shift << operator is used to "append" the new method. If the method already exists an exception will be thrown. If you want to replace an instance method you can use the = operator:

Code Block
Book.metaClass.toString = {-> title.toUpperCase() }