Groovy for Domain-specific Languages - Second Edition

(nextflipdebug2) #1

The Groovy Language


[ 60 ]

This code snippet shows how we can optionally use getter/setter methods to
manipulate the name field of our Customer class, or we can use field access syntax.
It's important to note that when we use the field access syntax customer.name,
we are not accessing the field directly. The appropriate getter or setter method is
called instead.


If you want to directly access the field without going through a getter
or setter, you can use the field dereference operator @. To access
customer.name directly, you would use [email protected].

A JavaBean version of our Customer class would require getters, setters, and a
default constructor, as follows:


public class Customer implements java.io.Serializable {
private int id;
private String name;

public Customer () {
}
public int getId() {
return this.id;
}
public void setId(final int id) {
this.id = id;
}
public String getName() {
return this.name;
}
public void setName(final String name) {
this.name = name;
}
}

GroovyBeans have a very useful initialization feature. We can pass Map to the
constructor of a bean that contains the names of the properties, along with an
associated initialization value:


given: "we initialize some beans with a Map of values"
def map = [id: 1, name: "Barney Rubble"]
def customer1 = new Customer( map )
def customer2 = new Customer( id: 2, name: "Fred Flintstone" )
expect: "the bean properties have been set"
customer1.id == 1
customer2.id == 2
customer1.name == "Barney Rubble"
customer2.name == "Fred Flintstone"

http://www.ebook3000.com
Free download pdf