Groovy Goodness: Direct Field Access In (Super) Classes

When we use the property syntax of Groovy to get the value for a property, Groovy will actually try to invoke a get method for that property if it is available. So for example if we have the statement user.name actually user.getName() is invoked. If we want to reference a property field directly, so bypassing the get method, we must place an @ in front of the property field name. In the previous example we would write user.@name to get the field value directly. The same rules apply for setting a value for a property with the Groovy syntax. If we write user.name = 'mrhaki' then actually user.setName('mrhaki') is invoked. We can use the @ prefix also to set a value without invoking the set method for that property. So in our example it would be user.@name = 'mrhaki' and the setName method is not used.

In the following example we have a class Person with a name property. We add a getName method which formats the name field and returns the value. In a subclass User we access the name property from the super class using the Groovy property syntax and with the @ prefix:

Written with Groovy 2.4.7.

Original blog post

This entry was posted in Coding, Groovy and tagged by mrhaki. Bookmark the permalink.

About mrhaki

My name is Hubert A. Klein Ikkink also known as mrhaki. I work at the great IT company JDriven. Here I work on projects with Groovy & Grails, Gradle and Spring. At JDriven we focus on SpringSource technologies. All colleagues want to learn new technologies, support craftmanship and are very eager to learn. This is truly a great environment to work in. You can contact me via Google+ or @mrhaki.

Leave a Reply

Your email address will not be published. Required fields are marked *