0
# Script Execution
1
2
High-level APIs for evaluating Groovy code, managing variable bindings, and creating reusable scripts with dynamic compilation capabilities.
3
4
## Capabilities
5
6
### GroovyShell
7
8
Shell for evaluating Groovy expressions and scripts with support for variable bindings and class loading.
9
10
```groovy { .api }
11
/**
12
* Shell for evaluating Groovy expressions and scripts
13
*/
14
class GroovyShell {
15
/** Create a new shell with default configuration */
16
GroovyShell()
17
18
/** Create a new shell with the given binding */
19
GroovyShell(Binding binding)
20
21
/** Create a new shell with custom ClassLoader */
22
GroovyShell(ClassLoader parent)
23
24
/** Create a new shell with ClassLoader and binding */
25
GroovyShell(ClassLoader parent, Binding binding)
26
27
/** Evaluate a Groovy script from string */
28
Object evaluate(String scriptText)
29
30
/** Evaluate a Groovy script from file */
31
Object evaluate(File file)
32
33
/** Evaluate a Groovy script from Reader */
34
Object evaluate(Reader reader)
35
36
/** Parse script text and return reusable Script object */
37
Script parse(String scriptText)
38
39
/** Parse script from file and return reusable Script object */
40
Script parse(File file)
41
42
/** Parse script text and return the generated Class */
43
Class parseClass(String text)
44
45
/** Parse script from file and return the generated Class */
46
Class parseClass(File file)
47
}
48
```
49
50
**Usage Examples:**
51
52
```groovy
53
// Basic script evaluation
54
def shell = new GroovyShell()
55
def result = shell.evaluate("2 + 2")
56
println result // 4
57
58
// Evaluation with variables
59
def binding = new Binding()
60
binding.setVariable("x", 10)
61
binding.setVariable("y", 5)
62
shell = new GroovyShell(binding)
63
result = shell.evaluate("x * y")
64
println result // 50
65
66
// Reusable scripts
67
def script = shell.parse('''
68
def calculate(a, b) {
69
return a * b + 10
70
}
71
calculate(x, y)
72
''')
73
result = script.run()
74
println result // 60
75
76
// File evaluation
77
def scriptFile = new File("myscript.groovy")
78
result = shell.evaluate(scriptFile)
79
```
80
81
### Variable Binding
82
83
Context for managing script variables and providing data exchange between Java and Groovy code.
84
85
```groovy { .api }
86
/**
87
* Variable binding context for scripts
88
*/
89
class Binding extends GroovyObjectSupport {
90
/** Create empty binding */
91
Binding()
92
93
/** Create binding with initial variable map */
94
Binding(Map variables)
95
96
/** Get a variable value by name */
97
Object getVariable(String name)
98
99
/** Set a variable value by name */
100
void setVariable(String name, Object value)
101
102
/** Get all variables as a Map */
103
Map getVariables()
104
105
/** Set all variables from a Map */
106
void setVariables(Map variables)
107
108
/** Check if a variable exists */
109
boolean hasVariable(String name)
110
111
/** Remove a variable */
112
Object removeVariable(String name)
113
}
114
```
115
116
**Usage Examples:**
117
118
```groovy
119
// Creating and using bindings
120
def binding = new Binding()
121
binding.setVariable("name", "Alice")
122
binding.setVariable("age", 30)
123
binding.setVariable("active", true)
124
125
def shell = new GroovyShell(binding)
126
def result = shell.evaluate('''
127
if (active) {
128
return "$name is $age years old and active"
129
} else {
130
return "$name is inactive"
131
}
132
''')
133
println result // "Alice is 30 years old and active"
134
135
// Sharing data between Java and Groovy
136
def binding = new Binding()
137
binding.setVariable("javaList", Arrays.asList(1, 2, 3, 4, 5))
138
139
def shell = new GroovyShell(binding)
140
shell.evaluate('''
141
// Groovy can manipulate Java objects
142
def sum = javaList.sum()
143
result = "Sum is: $sum"
144
''')
145
146
println binding.getVariable("result") // "Sum is: 15"
147
```
148
149
### GroovyClassLoader
150
151
ClassLoader that can dynamically compile and load Groovy classes at runtime.
152
153
```groovy { .api }
154
/**
155
* ClassLoader that can load Groovy classes at runtime
156
*/
157
class GroovyClassLoader extends URLClassLoader {
158
/** Create with default parent ClassLoader */
159
GroovyClassLoader()
160
161
/** Create with specified parent ClassLoader */
162
GroovyClassLoader(ClassLoader parent)
163
164
/** Parse and compile Groovy source text into a Class */
165
Class parseClass(String text)
166
167
/** Parse and compile Groovy source from file into a Class */
168
Class parseClass(File file)
169
170
/** Parse source with a specific file name (for error reporting) */
171
Class parseClass(String text, String fileName)
172
173
/** Load a class by name */
174
Class loadClass(String name)
175
176
/** Define a class from bytecode */
177
Class defineClass(String name, byte[] bytecode)
178
}
179
```
180
181
**Usage Examples:**
182
183
```groovy
184
// Dynamic class creation
185
def classLoader = new GroovyClassLoader()
186
def classText = '''
187
class DynamicClass {
188
String name
189
int value
190
191
def greet() {
192
return "Hello from $name with value $value"
193
}
194
}
195
'''
196
197
def dynamicClass = classLoader.parseClass(classText)
198
def instance = dynamicClass.newInstance()
199
instance.name = "Dynamic"
200
instance.value = 42
201
println instance.greet() // "Hello from Dynamic with value 42"
202
203
// Loading classes from files
204
def scriptFile = new File("MyGroovyClass.groovy")
205
def myClass = classLoader.parseClass(scriptFile)
206
def obj = myClass.newInstance()
207
```
208
209
### GroovyScriptEngine
210
211
Script engine for running Groovy scripts with dependency management and automatic recompilation.
212
213
```groovy { .api }
214
/**
215
* Script engine for running Groovy scripts with dependency management
216
*/
217
class GroovyScriptEngine {
218
/** Create engine with script root directories */
219
GroovyScriptEngine(String[] roots)
220
221
/** Create engine with URL roots */
222
GroovyScriptEngine(URL[] roots)
223
224
/** Run a script by name with the given binding */
225
Object run(String scriptName, Binding binding)
226
227
/** Get the GroovyCodeSource for a script */
228
GroovyCodeSource getGroovyCodeSource(String scriptName)
229
230
/** Get the ClassLoader used by this engine */
231
GroovyClassLoader getGroovyClassLoader()
232
}
233
```
234
235
**Usage Examples:**
236
237
```groovy
238
// Create script engine with script directories
239
def engine = new GroovyScriptEngine(["scripts", "lib"] as String[])
240
241
// Run scripts with bindings
242
def binding = new Binding()
243
binding.setVariable("input", "test data")
244
245
def result = engine.run("process.groovy", binding)
246
println "Script result: $result"
247
248
// Scripts can reference other scripts in the engine's path
249
// process.groovy might contain:
250
// import utils.Helper
251
// return Helper.processData(input)
252
```
253
254
### Evaluation Utilities
255
256
Quick evaluation utilities for simple expressions.
257
258
```groovy { .api }
259
/**
260
* Utility for evaluating Groovy expressions quickly
261
*/
262
class Eval {
263
/** Evaluate expression with self reference */
264
static Object me(Object self, String expression)
265
266
/** Evaluate expression with single variable x */
267
static Object x(Object x, String expression)
268
269
/** Evaluate expression with variables x and y */
270
static Object xy(Object x, Object y, String expression)
271
272
/** Evaluate expression with variables x, y, and z */
273
static Object xyz(Object x, Object y, Object z, String expression)
274
}
275
```
276
277
**Usage Examples:**
278
279
```groovy
280
// Quick expression evaluation
281
def result = Eval.me("'Hello World'.toUpperCase()")
282
println result // "HELLO WORLD"
283
284
// With variables
285
def nums = [1, 2, 3, 4, 5]
286
result = Eval.x(nums, "x.findAll { it % 2 == 0 }")
287
println result // [2, 4]
288
289
// Multiple variables
290
result = Eval.xy(10, 20, "x + y")
291
println result // 30
292
293
result = Eval.xyz(5, 10, 2, "x * y / z")
294
println result // 25
295
```