Chapter 7
[ 173 ]
def customerList = [ fred, barney]
when:
for (customer in customerList)
customer.prettyPrint()
then:
"""Customer has following properties
city: Bedrock
firstName: Fred
id: 1001
street: 1 Rock Road
surname: Flintstone
Customer has following properties
city: Bedrock
firstName: Barney
id: 1002
street: 2 Rock Road
surname: Rubble""" == output()
In the preceding code, we added a Customer.invokeMethod() method to the
Customer class. This allows us to intercept method invocations and respond to calls
to Customer.prettyPrint() even though this method does not exist. Remember
how in GroovyMarkup we appeared to be calling methods that did not exist? This is
the core of how GroovyMarkup works. The Customer.prettyPrint() method in the
previous code snippet is called a pretended method.
Understanding this, delegate, and owner
Like Java, Groovy has a this keyword that refers to the current or enclosing Java
object. In Java, we don't have any other context in which we can execute code except
in a class method. In an instance method, this will always refer to the instance
itself. In a static method, this has no meaning as the compiler won't allow us to
reference this in a static context.
In addition to the instance methods, Groovy has three additional execution contexts
to be aware of:
- Code running directly within a script where the enclosing object is the script
- Closure code where the enclosing object is either a script or an instance object
- Closure code where the enclosing object is another closure