Versions Compared


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


Overriding invokeMethod for static methods

ExpandoMetaClass - Overriding invokeMethod for static methods

It is also possible to override invokeMethod for static methods.

Overriding invokeMethod for static

As an example of overriding invokeMethod for static methods, take this simple example:

Code Block
class Stuff {
   static invokeMe() { "foo" }

Stuff.metaClass.'static'.invokeMethod = { String name, args ->
   def metaMethod = Stuff.metaClass.getStaticMetaMethod(name, args)
   def result
   if(metaMethod) result = metaMethod.invoke(delegate,args)
   else {
      result = "bar"

assert "foo" == Stuff.invokeMe()
assert "bar" == Stuff.doStuff()

So what is happening here? Well firstly we've overridden invokeMethod using the 'static' qualifier and by assigning it an appropriate closure, but in addition we first look-up a MetaMethod with the line:

Code Block
def metaMethod = delegate.class.metaClass.getStaticMetaMethod(name)

A MetaMethod in Groovy is a method that is known to exist on the MetaClass whether added at runtime or whatever, thus we check if there is an existing MetaMethod and if there isn't we simply return "bar", hence the behaviour of the assert statements is correct.

Useful References