Chapter 7
[ 165 ]
Expandos
An Expando is a dynamic representation of a typical Groovy bean. Expandos support
typical get and set style bean access but, in addition to this, they accept gets and
sets to arbitrary properties. If we try to access a non-existing property, the Expando
does not mind and, instead of causing an exception, it will return null. If we set a
non-existent property, the Expando will add that property and set the value. In order
to create an Expando, we instantiate an object of class groovy.util.Expando:
given:
def customer = new Expando()
expect:
customer.properties == [:]
customer.id == null
customer.properties == [:]
when:
customer.id = 1001
customer.firstName = "Fred"
customer.surname = "Flintstone"
customer.street = "1 Rock Road"
then:
customer.id == 1001
customer.properties == [
id:1001, firstName:'Fred',
surname:'Flintstone', street:'1 Rock Road']
The id field of customer is accessible on the Expando shown in the preceding
example even when it does not exist as a property of the bean. Once a property
has been set, it can be accessed by using the normal field getter, for example,
customer.id. Expandos are a useful extension to normal beans when we need
to be able to dump arbitrary properties into a bag and we don't want to write a
custom class to do so.