...
| Code Block |
|---|
class XmlBuilder {
def out
XmlBuilder(out) { this.out = out }
def invokeMethod(String name, args) {
out << "<$name>"
if(args[0] instanceof Closure) {
args[0].delegate = this
args[0].call()
}
else {
out << args[0].toString()
}
out << "</$name>"
}
}
def xml = new XmlBuilder(new StringBuffer())
xml.html {
head {
title "Hello World"
}
body {
p "Welcome!"
}
}
|
Another simple usage of invokeMethod is to provide simple AOP style around advice to existing methods. Here is a simple logging example implemented with invokeMethod:
| Code Block |
|---|
class MyClass implements GroovyInterceptable {
def invokeMethod(String name, args) {
System.out.println ("Beginning $name")
def metaMethod = metaClass.getMetaMethod(name, args)
def result = metaMethod.invoke(this, args)
System.out.println ("Completed $name")
return result
}
}
|
Overriding getProperty and setProperty
...