Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: fix example for overriding invokeMethod

...

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

Stuff.metaClass.invokeMethod = { String name, args ->
   def metaMethod = PersonStuff.metaClass.getMetaMethod(name, args)
    def result
   if(metaMethod) result = metaMethod.invoke(delegate,args)
   else {
      result = "bar"
   }
   result
}

def stf = new Stuff()

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

So what is happening here? Well firstly we've overriden invokeMethod 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.getMetaMethod(name)

...

Code Block
class Person {
   String name = "Fred"
}

Person.metaClass.getProperty = { String name ->
   def metaProperty = Person.metaClass.getMetaProperty(name)
    def result
   if(metaProperty) result = metaProperty.getProperty(delegate)
   else {
      result = "Flintstrone"
   }
   result
}

def p = new Person()

assert "Fred" == stf.name
assert "Flintstone" == stf.other

...