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 package groovy.lang;
36
37 /***
38 * Represents a property on a bean which may have a getter and/or a setter
39 *
40 * @author <a href="mailto:james@coredevelopers.net">James Strachan</a>
41 * @version $Revision: 1.2 $
42 */
43 public class MetaBeanProperty extends MetaProperty {
44
45 private MetaMethod getter;
46 private MetaMethod setter;
47
48 public MetaBeanProperty(String name, Class type, MetaMethod getter, MetaMethod setter) {
49 super(name, type);
50 this.getter = getter;
51 this.setter = setter;
52 }
53
54 /***
55 * @return the property of the given object
56 * @throws Exception if the property could not be evaluated
57 */
58 public Object getProperty(Object object) throws Exception {
59 if (getter == null) {
60
61 throw new GroovyRuntimeException("Cannot read write-only property: " + name);
62 }
63 return getter.invoke(object, MetaClass.EMPTY_ARRAY);
64 }
65
66 /***
67 * Sets the property on the given object to the new value
68 *
69 * @param object on which to set the property
70 * @param newValue the new value of the property
71 * @throws Exception if the property could not be set
72 */
73 public void setProperty(Object object, Object newValue) {
74 if(setter == null) {
75 throw new GroovyRuntimeException("Cannot set read-only property: " + name);
76 }
77
78 try {
79
80 if(getType() == String.class && !(newValue instanceof String))
81 newValue = newValue.toString();
82
83 setter.invoke(object, new Object[] { newValue });
84 }
85 catch(Exception e) {
86 throw new GroovyRuntimeException("Cannot set property: " + name +
87 " reason: " + e.getMessage(), e);
88 }
89 }
90
91 public MetaMethod getGetter() {
92 return getter;
93 }
94
95 public MetaMethod getSetter() {
96 return setter;
97 }
98
99 /***
100 * this is for MetaClass to patch up the object later when looking for get*() methods
101 */
102 void setGetter(MetaMethod getter) {
103 this.getter = getter;
104 }
105
106 /***
107 * this is for MetaClass to patch up the object later when looking for set*() methods
108 */
109 void setSetter(MetaMethod setter) {
110 this.setter = setter;
111 }
112 }