-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbeans.groovy
73 lines (46 loc) · 1.89 KB
/
beans.groovy
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
/*
Groovy Beans
GroovyBeans are JavaBeans but using a much simpler syntax
When Groovy is compiled to bytecode, the following rules are used.
* If the name is declared with an access modifier (public, private or
protected) then a field is generated.
* A name declared with no access modifier generates a private field with
public getter and setter (i.e. a property).
* If a property is declared final the private field is created final and no
setter is generated.
* You can declare a property and also declare your own getter or setter.
* You can declare a property and a field of the same name, the property will
use that field then.
* If you want a private or protected property you have to provide your own
getter and setter which must be declared private or protected.
* If you access a property from within the class the property is defined in
at compile time with implicit or explicit this (for example this.foo, or
simply foo), Groovy will access the field directly instead of going though
the getter and setter.
* If you access a property that does not exist using the explicit or
implicit foo, then Groovy will access the property through the meta class,
which may fail at runtime.
*/
class Foo {
// read only property
final String name = "Roberto"
// read only property with public getter and protected setter
String language
protected void setLanguage(String language) { this.language = language }
// dynamically typed property
def lastName
}
def Foo foo = new Foo()
// Throws excepion
// foo.name = 'Carlos'
assert foo.name == 'Roberto'
foo.language = 'pl'
println foo.language
foo.setLanguage('en')
println foo.language
foo.setLastName(new java.util.Date())
println foo.lastName
foo.setLastName(5)
println foo.lastName
foo.setLastName('Santana')
println foo.lastName