GroovyBeans就是普通的JavaBeans,但其额外的优势是它会自动生成公共的访问器方法(accessor methods,getters和setter方法)。清单4.27给出一个例子。
清单 4.27 Employee GroovyBean
class Employee{
String firstName, lastName
def id
String dept
String getName(){
return firstName + ' ' + lastName
}
}
Employee employee = new Employee()
employee.firstName = 'Bashar'
employee.lastName = 'Abdul'
assert employee.getFirstName() == 'Bashar'
assert employee.lastName == 'Abdul'
assert employee.name == 'Bashar Abdul'
如果您想重载getter或setter方法的默认行为,只需依据Java命名规则在类中定义属性相对应的方法,getPropertyName和setPropertyName。
Groovy还有一个特殊的操作符.@,它可在不使用访问器方法的情况下,直接访问字段甚至私有的字段,如清单4.28。
清单4.28 使用.@操作符直接访问字段
class Employee {
private String name
def setName(name){
this.name = name
}
def getName(){
return name.toUpperCase()
}
}
def employee = new Employee(name: 'Bashar')
assert employee.name == 'BASHAR'
assert employee.@name == 'Bashar'
您可使用properties属性,获得bean所有属性的映射,例如清单4.29.
清单4.29 获取Bean所有属性
class Employee {
String firstName = 'Bashar'
String lastName
private id
def title
}
Employee employee = new Employee()
assert employee.properties.containsKey('firstName')
assert employee.properties.containsValue('Bashar')
assert employee.properties.containsKey('lastName')
assert employee.properties.containsKey('title')
assert employee.properties.containsKey('id') == false