Versions Compared

Key

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

...

Since 1.5, Groovy supports the concept of "methodMissing". This differs from invokeMethod in that it is only invoked in the case of failed method dispatch.

There are a couple of important aspects to this behaviour:

  1. Since method/propertyMissing only occur in the case of failed dispatch, they are expensive to execute
  2. Since method/propertyMissing aren't intercepting EVERY method call like invokeMethod they can be more efficient with a few meta-programming tricks

Using methodMissing with dynamic method registration

...

For example consider dynamic finders in GORM. These are implemented in terms of methodMissing. How does it work? The code resembles something like this:

Code Block

class GORM {

   def dynamicMethods = [...] // an array of dynamic methods that use regex
   def methodMissing(String name, args) {
       def method = dynamicMethods.find { it.match(name) }
       if(method) {
          GORM.metaClass."$name" = { Object[] varArgs ->
             method.invoke(delegate, name, varArgs)
          }
          return method.invoke(delegate,name, args)
       }
       else throw new MissingMethodException(name, delegate, args)
   }
}

...

Groovy also supports propertyMissing for dealing with property resolution attempts. For a getter you use a propertyMissing definition that takes a String argument:

Code Block

class Foo {
   def propertyMissing(String name) { name }
}
def f = new Foo()

assertEquals "boo", f.boo

For a setters you add a second propertyMissing definition that takes a value argument:

Code Block

class Foo {
   def storage = [:]
   def propertyMissing(String name, value) { storage[name] = value }
   def propertyMissing(String name) { storage[name] }
}
def f = new Foo()
f.foo = "bar"

assertEquals "bar", f.foo

...