Groovy入门系列之GroovyBean

3 views
Skip to first unread message

xiyuan76

unread,
Nov 20, 2009, 1:32:11 AM11/20/09
to Groovy用户组
1.属性和域

在GroovyBean中,实际定义的是属性,而非域。对属性的访问实际上是调用的是对应的getter/setter,即:

* a.b=… //对应a.setB
* …=a.b //对应a.getB

如果想要定义自己的getter/setter,那么只需实现它们就行了。

如果想要直接访问域,可以用.@:a.@b 实际访问的就是属性b对应的域。

class A{
def b
def getB(){
return 'B'
}
}
def a = new A(b:'b')
assert a.b == 'B'
assert a.@b == 'b'


2.GPath

在Groovy中可以使用GPath来访问对象的属性。而且,它也可以应用在内嵌的对象上。形如:“对象.属性”。

class A{
def p
}
class B{
def p1
A p2
}
def a= new A(p:'China')
def b= new B(p1:"Xi'an", p2:a)
b.p1 + ", "+ b.p2.p == "Xi'an, China"

Reply all
Reply to author
Forward
0 new messages