Elementary Metaprogramming

class Sample {
}

//Btw, you can skip the semi-colons
def s1 = new Sample()

try {
  s1.foo()
} catch (Exception e) {
  //Note the "GString", and the use of an implicit property getter
  println "It didn't work: ${e.message}"  
}


//metaClass is a property of Object
Sample.metaClass.foo = { -> println "It worked this time!" }


def s2 = new Sample()
s2.foo()


try {
  s1.foo()
} catch (Exception e) {
  //Note the "GString", and the use of an implicit property getter
  println "It didn't work: ${e.message}"  
}

[bruce@kimura presentation]$ groovy test.groovy
It didn't work: No signature of method: Sample.foo() is applicable for argument types: () values: {}
It worked this time!
It didn't work: No signature of method: Sample.foo() is applicable for argument types: () values: {}

Next