Groovy - Groovy Beans

GroovyBeans are JavaBeans but using a much simpler syntax.
Here's an example:

import java.util.Date

class Customer {
    // properties
    Integer id
    String name
    Date dob
    
    // sample code
    static void main(args) {
        customer = new Customer(id:1, name:"Gromit", dob:new Date())
        println("Hello ${customer.name}")
    }
}
Hello Gromit

Notice how the properties look just like public fields. You can also set named properties in a bean constructor in Groovy. In Groovy, fields and properties have been merged so that they act and look the same. So, the Groovy code above is equivalent to the following Java code:

import java.util.Date;

public class Customer {
    // properties
    private Integer id;
    private String name;
    private Date dob;
    
    public Integer getId() {
        return this.id;
    }
    
    public String getName() {
        return this.name;
    }
    
    public Date getDob() {
        return this.dob;
    }
    
    public void setId(Integer id) {
        this.id = id;
    }
    
    public void setName(String name) {
        this.name = name;
    }
    
    public void setDob(Date dob) {
        this.dob = dob;
    }
    
    // sample code
    public static void main(String[] args) {
        Customer customer = new Customer();
        customer.setId(1);
        customer.setName("Gromit");
        customer.setDob(new Date());
       
        println("Hello " + customer.getName());
    }
}

Property and field rules

When Groovy is compiled to bytecode, the following rules are used.


So, for example, you could create a read only property or a public read-only property with a protected setter like this:

class Foo {
    // read only property
    private String name
    public String getName() { return name }
    
    // read only property with protected setter
    Integer amount
    protected void setAmount(Integer amount) { this.amount = amount }
    
    // dynamically typed property
    cheese
}