Friday, May 20, 2011

Why Does This Work?

class Person {
    def name
    def age
}

jill = new Person(name: 'Jill', age: 21) 
john = new Person(name: 'John', age: 12)
jorge = [name: "Jorge", age: 3]

def printPerson(x) {
    println "This is ${x.name} who is ${x.age}"
}

printPerson(jill)
printPerson(john)
printPerson(jorge)
This is Jill who is 21
This is John who is 12
This is Jorge who is 3

Now, a slightly different version shows the accessor is called implicitly when using the field name

class Person {
    def name
    def age
    
    String getName() {
        return "Calling the accessor ..."
    }
}

jill = new Person(name: 'Jill', age: 21) 
john = new Person(name: 'John', age: 12)
jorge = [name: "Jorge", age: 3]

def printPerson(x) {
    println "This is ${x.name} who is ${x.age}"
}

printPerson(jill)
printPerson(john)
printPerson(jorge)
This is Calling the accessor ... who is 21
This is Calling the accessor ... who is 12
This is Jorge who is 3

When the groovy code is compiled and javap run on the class, I find that there is no getName() method. There is however, a getProperty(java.lang.String) method that returns an object. Going out on a limb, I'm guessing that getProperty is called with the field name passed to it, something like java.util.Calendar.get(java.util.Calendar.DAY_OF_MONTH).

Blog Archive