0
# Core Language Features
1
2
This document covers the fundamental Groovy language constructs including script execution, dynamic objects, closures, metaprogramming, and the core runtime system.
3
4
## Script Execution
5
6
### GroovyShell
7
8
The main entry point for executing Groovy scripts dynamically at runtime.
9
10
```groovy { .api }
11
class GroovyShell {
12
// Constructors
13
GroovyShell()
14
GroovyShell(Binding binding)
15
GroovyShell(ClassLoader parent)
16
GroovyShell(ClassLoader parent, Binding binding)
17
GroovyShell(CompilerConfiguration config)
18
GroovyShell(ClassLoader parent, CompilerConfiguration config)
19
GroovyShell(Binding binding, CompilerConfiguration config)
20
GroovyShell(ClassLoader parent, Binding binding, CompilerConfiguration config)
21
GroovyShell(GroovyShell shell)
22
23
// Basic evaluate methods
24
Object evaluate(String scriptText)
25
Object evaluate(String scriptText, String fileName)
26
Object evaluate(String scriptText, String fileName, String codeBase)
27
Object evaluate(File scriptFile)
28
Object evaluate(Reader in)
29
Object evaluate(Reader in, String fileName)
30
Object evaluate(URI uri)
31
Object evaluate(GroovyCodeSource codeSource)
32
33
// Basic parse methods
34
Script parse(String scriptText)
35
Script parse(String scriptText, String fileName)
36
Script parse(File scriptFile)
37
Script parse(Reader reader, String fileName)
38
Script parse(Reader in)
39
Script parse(URI uri)
40
Script parse(GroovyCodeSource codeSource)
41
42
// Run methods with arguments
43
Object run(File scriptFile, List<String> list)
44
Object run(File scriptFile, String[] args)
45
Object run(String scriptText, String fileName, List<String> list)
46
Object run(String scriptText, String fileName, String[] args)
47
Object run(GroovyCodeSource source, List<String> args)
48
Object run(GroovyCodeSource source, String[] args)
49
Object run(URI source, List<String> args)
50
Object run(URI source, String[] args)
51
Object run(Reader in, String fileName, List<String> list)
52
Object run(Reader in, String fileName, String[] args)
53
54
// Variable management
55
Object getVariable(String name)
56
void setVariable(String name, Object value)
57
void removeVariable(String name)
58
59
// Properties and context
60
Object getProperty(String property)
61
void setProperty(String property, Object newValue)
62
Binding getContext()
63
GroovyClassLoader getClassLoader()
64
65
// Utility methods
66
void resetLoadedClasses()
67
static void main(String[] args)
68
}
69
```
70
71
Usage example:
72
```groovy
73
def shell = new GroovyShell()
74
def result = shell.evaluate('Math.max(5, 10)')
75
assert result == 10
76
77
def binding = new Binding([x: 10, y: 20])
78
shell = new GroovyShell(binding)
79
result = shell.evaluate('x + y')
80
assert result == 30
81
```
82
83
### GroovyScriptEngine
84
85
Script engine with caching and dependency management for improved performance.
86
87
```groovy { .api }
88
class GroovyScriptEngine {
89
GroovyScriptEngine(String[] roots)
90
GroovyScriptEngine(String[] roots, ClassLoader parent)
91
GroovyScriptEngine(ResourceConnector rc)
92
GroovyScriptEngine(ResourceConnector rc, ClassLoader parent)
93
94
Object run(String scriptName, Binding binding)
95
Class loadScriptByName(String scriptName)
96
GroovyClassLoader getGroovyClassLoader()
97
CompilerConfiguration getConfig()
98
}
99
```
100
101
### GroovyClassLoader
102
103
Dynamic class loader for compiling and loading Groovy classes at runtime.
104
105
```groovy { .api }
106
class GroovyClassLoader extends ClassLoader {
107
GroovyClassLoader()
108
GroovyClassLoader(ClassLoader parent)
109
GroovyClassLoader(ClassLoader parent, CompilerConfiguration config)
110
111
Class parseClass(String text)
112
Class parseClass(String text, String fileName)
113
Class parseClass(File file)
114
Class parseClass(InputStream in, String fileName)
115
Class parseClass(URL url)
116
117
void addClasspath(String path)
118
void clearCache()
119
CompilerConfiguration getConfig()
120
}
121
```
122
123
## Variable Binding
124
125
### Binding
126
127
Container for script variables and their values.
128
129
```groovy { .api }
130
class Binding {
131
Binding()
132
Binding(Map variables)
133
Binding(String[] args)
134
135
Object getVariable(String name)
136
void setVariable(String name, Object value)
137
boolean hasVariable(String name)
138
void removeVariable(String name)
139
Map getVariables()
140
void setProperty(String property, Object newValue)
141
Object getProperty(String property)
142
}
143
```
144
145
Usage example:
146
```groovy
147
def binding = new Binding()
148
binding.setVariable('greeting', 'Hello')
149
binding.setVariable('name', 'World')
150
151
def shell = new GroovyShell(binding)
152
def result = shell.evaluate('"$greeting, $name!"')
153
assert result == 'Hello, World!'
154
```
155
156
## Closures
157
158
### Closure
159
160
First-class functions with lexical scoping and powerful features.
161
162
```groovy { .api }
163
abstract class Closure<V> implements Cloneable, Runnable, GroovyCallable<V> {
164
static final int DELEGATE_FIRST = 1
165
static final int DELEGATE_ONLY = 2
166
static final int OWNER_FIRST = 3
167
static final int OWNER_ONLY = 4
168
static final int TO_SELF = 5
169
170
Object call()
171
Object call(Object... args)
172
Object call(Object arguments)
173
174
Closure<V> curry(Object... args)
175
Closure<V> rcurry(Object... args)
176
Closure<V> ncurry(int n, Object... args)
177
178
Closure<V> memoize()
179
Closure<V> memoizeAtMost(int maxCacheSize)
180
Closure<V> memoizeAtLeast(int minCacheSize)
181
Closure<V> memoizeBetween(int minCacheSize, int maxCacheSize)
182
183
Object getDelegate()
184
void setDelegate(Object delegate)
185
Object getOwner()
186
Object getThisObject()
187
int getResolveStrategy()
188
void setResolveStrategy(int resolveStrategy)
189
190
int getMaximumNumberOfParameters()
191
Class[] getParameterTypes()
192
193
Closure<V> clone()
194
Closure<V> asWritable()
195
}
196
```
197
198
Usage examples:
199
```groovy
200
// Basic closure
201
def greet = { name -> "Hello, $name!" }
202
assert greet('World') == 'Hello, World!'
203
204
// Curry parameters
205
def multiply = { x, y -> x * y }
206
def double = multiply.curry(2)
207
assert double(5) == 10
208
209
// Delegate usage
210
def obj = [name: 'Groovy']
211
def closure = { "Hello, $name!" }
212
closure.delegate = obj
213
closure.resolveStrategy = Closure.DELEGATE_FIRST
214
assert closure() == 'Hello, Groovy!'
215
```
216
217
## Dynamic Objects
218
219
### Expando
220
221
Dynamic object that allows runtime addition of properties and methods.
222
223
```groovy { .api }
224
class Expando implements GroovyObject {
225
Expando()
226
Expando(Map<String, Object> properties)
227
228
Object invokeMethod(String name, Object args)
229
Object getProperty(String property)
230
void setProperty(String property, Object newValue)
231
MetaClass getMetaClass()
232
void setMetaClass(MetaClass metaClass)
233
234
String toString()
235
}
236
```
237
238
Usage example:
239
```groovy
240
def person = new Expando()
241
person.name = 'John'
242
person.age = 30
243
person.greet = { "Hello, I'm $name and I'm $age years old" }
244
person.birthday = { age++ }
245
246
assert person.greet() == "Hello, I'm John and I'm 30 years old"
247
person.birthday()
248
assert person.age == 31
249
```
250
251
## Metaprogramming
252
253
### MetaClass System
254
255
The metaclass system enables runtime modification of class behavior.
256
257
```groovy { .api }
258
interface MetaClass {
259
Object invokeMethod(Object object, String methodName, Object[] arguments)
260
Object invokeMethod(Object object, String methodName, Object arguments)
261
Object invokeStaticMethod(Object object, String methodName, Object[] arguments)
262
Object invokeConstructor(Object[] arguments)
263
264
Object getProperty(Object object, String property)
265
void setProperty(Object object, String property, Object newValue)
266
267
List<MetaMethod> getMethods()
268
List<MetaMethod> getMetaMethods()
269
MetaMethod getMetaMethod(String name, Class[] argTypes)
270
MetaMethod getStaticMetaMethod(String name, Class[] argTypes)
271
272
List<MetaProperty> getProperties()
273
MetaProperty getMetaProperty(String name)
274
boolean hasProperty(Object obj, String name)
275
276
void addMetaMethod(MetaMethod metaMethod)
277
void addMetaProperty(MetaProperty metaProperty)
278
}
279
```
280
281
### ExpandoMetaClass
282
283
Runtime metaclass modification capabilities.
284
285
```groovy { .api }
286
class ExpandoMetaClass extends MetaClassImpl {
287
ExpandoMetaClass(Class theClass)
288
ExpandoMetaClass(Class theClass, boolean register)
289
ExpandoMetaClass(Class theClass, boolean register, boolean allowChangesAfterInit)
290
291
void registerInstanceMethod(String name, Closure closure)
292
void registerStaticMethod(String name, Closure closure)
293
void registerConstructor(Closure closure)
294
295
Object getProperty(String property)
296
void setProperty(String property, Object newValue)
297
298
void initialize()
299
boolean isModified()
300
void enableGlobally()
301
static void enableGlobally()
302
}
303
```
304
305
Usage example:
306
```groovy
307
// Add method to existing class
308
String.metaClass.isPalindrome = {
309
delegate == delegate.reverse()
310
}
311
assert 'racecar'.isPalindrome() == true
312
assert 'hello'.isPalindrome() == false
313
314
// Add static method
315
Integer.metaClass.static.between = { int a, int b ->
316
(a..b).toList()
317
}
318
assert Integer.between(1, 5) == [1, 2, 3, 4, 5]
319
```
320
321
## String Interpolation
322
323
### GString
324
325
Groovy's template string implementation with embedded expressions.
326
327
```groovy { .api }
328
abstract class GString implements Comparable, CharSequence, Writable, Buildable {
329
abstract Object[] getValues()
330
abstract String[] getStrings()
331
332
String toString()
333
Writer writeTo(Writer out)
334
int length()
335
char charAt(int index)
336
CharSequence subSequence(int start, int end)
337
338
int compareTo(Object that)
339
boolean equals(Object that)
340
int hashCode()
341
}
342
```
343
344
Usage example:
345
```groovy
346
def name = 'World'
347
def number = 42
348
def gstring = "Hello, $name! The answer is ${number * 2}."
349
assert gstring.toString() == 'Hello, World! The answer is 84.'
350
assert gstring.values == ['World', 84]
351
assert gstring.strings == ['Hello, ', '! The answer is ', '.']
352
```
353
354
## Ranges
355
356
### Range Implementations
357
358
Groovy provides several range implementations for different data types.
359
360
```groovy { .api }
361
class IntRange implements Range<Integer> {
362
IntRange(int from, int to)
363
IntRange(boolean inclusive, int from, int to)
364
365
boolean contains(Object value)
366
boolean containsWithinBounds(Object value)
367
Integer get(int index)
368
int size()
369
List<Integer> step(int stepSize)
370
List<Integer> step(int stepSize, Closure closure)
371
String inspect()
372
boolean isReverse()
373
IntRange reverse()
374
}
375
376
class ObjectRange implements Range<Comparable> {
377
ObjectRange(Comparable from, Comparable to)
378
ObjectRange(Comparable from, Comparable to, boolean inclusive)
379
380
void step(int step, Closure closure)
381
List step(int step)
382
int size()
383
Comparable get(int index)
384
boolean contains(Object obj)
385
boolean containsWithinBounds(Object obj)
386
}
387
```
388
389
Usage examples:
390
```groovy
391
// Integer ranges
392
def range1 = 1..5
393
def range2 = 1..<5 // exclusive
394
assert range1.contains(5) == true
395
assert range2.contains(5) == false
396
assert range1.size() == 5
397
assert range2.size() == 4
398
399
// Object ranges
400
def letters = 'a'..'e'
401
assert letters.contains('c') == true
402
assert letters.size() == 5
403
404
// Range iteration
405
(1..3).each { println it }
406
(1..10).step(2) { println it } // prints 1, 3, 5, 7, 9
407
```
408
409
## System Information
410
411
### GroovySystem
412
413
System-level information and version details.
414
415
```groovy { .api }
416
class GroovySystem {
417
static String getVersion()
418
static MetaClassRegistry getMetaClassRegistry()
419
static boolean isUseReflection()
420
static void setUseReflection(boolean useReflection)
421
}
422
```
423
424
Usage example:
425
```groovy
426
println "Groovy version: ${GroovySystem.version}"
427
def registry = GroovySystem.metaClassRegistry
428
println "MetaClass registry: $registry"
429
```