Skip to end of metadata
Go to start of metadata

You are viewing an old version of this page. View the current version.

Compare with Current View Page History

Version 1 Next »

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

Error rendering macro 'code': Invalid value specified for parameter 'lang'
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}")
    }
}
Error rendering macro 'code': Invalid value specified for parameter 'lang'
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 above is equivlent to the
following Java code...

h2 Property and field rules

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

  • if the property is private, then a Java field is used to represent the property
  • if a public or protected property is declared (properties are public by default) then a public or protected getter and setter are created along with a private Java field
  • if you don't declare any getters or setters they are automatically created for you at the bytecode level for public or protected properties.
  • if you create a public or protected property you can overload any auto-created methods

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

Error rendering macro 'code': Invalid value specified for parameter 'lang'
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
}
  • No labels