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

Using methodMissing & propertyMissing

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

Typically when using methodMissing the code will react in some way that makes it possible for the next time the same method is called, that it goes through the regular Groovy method dispatch logic.

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

Notice how, if we find a method to invoke then we dynamically register a new method on the fly using ExpandoMetaClass. This is so that the next time the same method is called it is more efficient. This way methodMissing doesn't have the overhead of invokeMethod AND is not expensive for the second call

Using propertyMissing

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

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

As with methodMissing you will likely want to dynamically register new properties at runtime to improve the performance of you code.

Static methods and properties

You can add methodMissing and propertyMissing that deals with static methods and properties via ExpandoMetaClass

  • No labels