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 package groovy.lang;
47
48 import java.util.HashMap;
49 import java.util.Map;
50
51 /***
52 * Represents the variable bindings of a script which can be altered
53 * from outside the script object or created outside of a script and passed
54 * into it.
55 *
56 * @author <a href="mailto:james@coredevelopers.net">James Strachan</a>
57 * @version $Revision: 1.5 $
58 */
59 public class Binding extends GroovyObjectSupport {
60 private Map variables;
61
62 public Binding() {
63 variables = new HashMap();
64 }
65
66 public Binding(Map variables) {
67 this.variables = variables;
68 }
69
70 /***
71 * A helper constructor used in main(String[]) method calls
72 *
73 * @param args are the command line arguments from a main()
74 */
75 public Binding(String[] args) {
76 this();
77 setVariable("args", args);
78 }
79
80 /***
81 * @param name the name of the variable to lookup
82 * @return the variable value
83 */
84 public Object getVariable(String name) {
85 Object result = variables.get(name);
86
87 if (result == null && !variables.containsKey(name)) {
88 throw new MissingPropertyException("The property '" + name + "' is missing from the binding.",
89 name, Binding.class);
90 }
91
92 return result;
93 }
94
95 /***
96 * Sets the value of the given variable
97 * @param name the name of the variable to set
98 * @param value the new value for the given variable
99 */
100 public void setVariable(String name, Object value) {
101 variables.put(name, value);
102 }
103
104 public Map getVariables() {
105 return variables;
106 }
107
108 /***
109 * Overloaded to make variables appear as bean properties or via the subscript operator
110 */
111 public Object getProperty(String property) {
112 /*** @todo we should check if we have the property with the metaClass instead of try/catch */
113 try {
114 return super.getProperty(property);
115 }
116 catch (MissingPropertyException e) {
117 return getVariable(property);
118 }
119 }
120
121 /***
122 * Overloaded to make variables appear as bean properties or via the subscript operator
123 */
124 public void setProperty(String property, Object newValue) {
125 /*** @todo we should check if we have the property with the metaClass instead of try/catch */
126 try {
127 super.setProperty(property, newValue);
128 }
129 catch (MissingPropertyException e) {
130 setVariable(property, newValue);
131 }
132 }
133
134 }