October 27, 2009

Groovy Goodness: Getting and Setting Properties

In Groovy we can set values for properties with a simple assignment using the = operator. Groovy will invoke the set for us. At first sight we might think Groovy sets the variable in the class directly, but that is not true, because the set method is invoked. To get the value of a property we can use dot (.) notation instead of the get method.

Let's see this in action in code. We first create a simple JavaBean in Java code and then we set and get the property in different ways.

// Simple Java Bean.
public class Simple {
    private String text;
    public Simple() { 

    public String getMessage() { 
        return "GET " + text; 

    public void setMessage(final String text) {
        this.text = "SET " + text

Now some Groovy code to get and set values for the text property.

def s1 = new Simple()
s1.setMessage('Old style')
assert 'GET SET Old style' == s1.getMessage()
s1.setMessage 'A bit more Groovy'  // No parenthesis.
assert 'GET SET A bit more Groovy' == s1.getMessage()

def s2 = new Simple(message: 'Groovy constructor')  // Named parameter in constructor.
assert 'GET SET Groovy constructor' == s1.getMessage()

def s3 = new Simple()
s3.message = 'Groovy style'  // = assigment for property.
assert 'GET SET Groovy style' == s3.message  // get value with . notation.