0
# Core Language Runtime
1
2
Essential runtime classes and interfaces that enable Groovy's dynamic behavior, meta-programming capabilities, and integration with the JVM. These components form the foundation of Groovy's language features including closures, scripts, meta-programming, and dynamic method dispatch.
3
4
## Capabilities
5
6
### GroovyObject Interface
7
8
The root interface that all Groovy objects implement, providing the foundation for dynamic method and property access.
9
10
```java { .api }
11
interface GroovyObject {
12
/**
13
* Invokes a method on this object with the given name and arguments.
14
*/
15
Object invokeMethod(String name, Object args);
16
17
/**
18
* Gets the value of a property.
19
*/
20
Object getProperty(String propertyName);
21
22
/**
23
* Sets the value of a property.
24
*/
25
void setProperty(String propertyName, Object newValue);
26
27
/**
28
* Gets the MetaClass for this object.
29
*/
30
MetaClass getMetaClass();
31
32
/**
33
* Sets the MetaClass for this object.
34
*/
35
void setMetaClass(MetaClass metaClass);
36
}
37
```
38
39
### MetaClass System
40
41
The meta-programming interface that controls method dispatch and property access for objects.
42
43
```java { .api }
44
interface MetaClass {
45
/**
46
* Invokes a method on the given object.
47
*/
48
Object invokeMethod(Object object, String methodName, Object[] arguments);
49
50
/**
51
* Gets a property value from the given object.
52
*/
53
Object getProperty(Object object, String propertyName);
54
55
/**
56
* Sets a property value on the given object.
57
*/
58
void setProperty(Object object, String propertyName, Object newValue);
59
60
/**
61
* Checks if the object responds to the given method name.
62
*/
63
boolean respondsTo(Object obj, String name);
64
65
/**
66
* Checks if the object has the given property.
67
*/
68
MetaProperty hasProperty(Object obj, String name);
69
70
/**
71
* Gets all methods available on this MetaClass.
72
*/
73
List<MetaMethod> getMethods();
74
75
/**
76
* Gets all properties available on this MetaClass.
77
*/
78
List<MetaProperty> getProperties();
79
}
80
81
class ExpandoMetaClass implements MetaClass {
82
/**
83
* Defines a new property on this MetaClass.
84
*/
85
void defineProperty(String name, Object value);
86
87
/**
88
* Adds a method using the << operator.
89
*/
90
void leftShift(Map<String, Closure> methodMap);
91
92
/**
93
* Adds a property using the >> operator.
94
*/
95
void rightShift(Map<String, Object> propertyMap);
96
97
/**
98
* Enables global changes to this MetaClass.
99
*/
100
void enableGlobally();
101
}
102
```
103
104
### Groovy Shell
105
106
Shell for parsing and executing Groovy code dynamically at runtime.
107
108
```java { .api }
109
class GroovyShell {
110
/**
111
* Creates a new GroovyShell with default settings.
112
*/
113
GroovyShell();
114
115
/**
116
* Creates a new GroovyShell with the specified ClassLoader.
117
*/
118
GroovyShell(ClassLoader parent);
119
120
/**
121
* Creates a new GroovyShell with the specified Binding.
122
*/
123
GroovyShell(Binding binding);
124
125
/**
126
* Creates a new GroovyShell with ClassLoader and Binding.
127
*/
128
GroovyShell(ClassLoader parent, Binding binding);
129
130
/**
131
* Parses the given script text and returns a Script object.
132
*/
133
Script parse(String scriptText);
134
135
/**
136
* Parses the given file and returns a Script object.
137
*/
138
Script parse(File file);
139
140
/**
141
* Evaluates the given script text and returns the result.
142
*/
143
Object evaluate(String scriptText);
144
145
/**
146
* Evaluates the given file and returns the result.
147
*/
148
Object evaluate(File file);
149
150
/**
151
* Runs the given script with arguments.
152
*/
153
Object run(String scriptText, String[] args);
154
}
155
```
156
157
### GroovyClassLoader
158
159
ClassLoader implementation for loading and compiling Groovy classes at runtime.
160
161
```java { .api }
162
class GroovyClassLoader extends URLClassLoader {
163
/**
164
* Creates a new GroovyClassLoader.
165
*/
166
GroovyClassLoader();
167
168
/**
169
* Creates a new GroovyClassLoader with the specified parent.
170
*/
171
GroovyClassLoader(ClassLoader parent);
172
173
/**
174
* Parses a class from the given text.
175
*/
176
Class<?> parseClass(String text);
177
178
/**
179
* Parses a class from the given file.
180
*/
181
Class<?> parseClass(File file);
182
183
/**
184
* Loads a class by name.
185
*/
186
Class<?> loadClass(String name);
187
188
/**
189
* Clears the internal cache.
190
*/
191
void clearCache();
192
}
193
```
194
195
### Extension Methods and DefaultGroovyMethods
196
197
Groovy adds hundreds of extension methods to existing Java classes through DefaultGroovyMethods, providing powerful collection processing, string manipulation, and utility functions.
198
199
```java { .api }
200
/**
201
* Extension methods added to Object and its subclasses
202
*/
203
class DefaultGroovyMethods {
204
/**
205
* Collection processing methods
206
*/
207
static <T> List<T> findAll(Collection<T> self, Closure closure);
208
static <T> T find(Collection<T> self, Closure closure);
209
static <T> T inject(Collection<T> self, T initialValue, Closure closure);
210
static <T> List<T> collect(Collection<T> self, Closure closure);
211
static <T> List<T> sort(Collection<T> self);
212
static <T> List<T> sort(Collection<T> self, Closure closure);
213
static <T> List<T> unique(Collection<T> self);
214
static <T> Map<Object, List<T>> groupBy(Collection<T> self, Closure closure);
215
static int sum(Collection<Number> self);
216
static <T> T max(Collection<T> self);
217
static <T> T min(Collection<T> self);
218
219
/**
220
* String manipulation methods
221
*/
222
static boolean isNumber(String self);
223
static String padLeft(String self, int numberOfCharacters);
224
static String padRight(String self, int numberOfCharacters);
225
static String center(String self, int numberOfCharacters);
226
static String capitalize(String self);
227
static List<String> tokenize(String self);
228
static List<String> tokenize(String self, String token);
229
230
/**
231
* Iteration methods
232
*/
233
static void times(Integer self, Closure closure);
234
static void upto(Number self, Number to, Closure closure);
235
static void downto(Number self, Number to, Closure closure);
236
237
/**
238
* General utility methods
239
*/
240
static String dump(Object self);
241
static Object identity(Object self, Closure closure);
242
static Object with(Object self, Closure closure);
243
static boolean asBoolean(Object self);
244
static String toString(Object self);
245
}
246
247
/**
248
* String-specific extension methods
249
*/
250
class StringGroovyMethods {
251
static String multiply(String self, int factor);
252
static String reverse(String self);
253
static boolean startsWith(String self, String prefix);
254
static boolean endsWith(String self, String suffix);
255
static String[] split(String self, String regex);
256
static String replaceAll(String self, String regex, String replacement);
257
static String replaceFirst(String self, String regex, String replacement);
258
static List<String> readLines(String self);
259
static void eachLine(String self, Closure closure);
260
}
261
```
262
263
**Usage Examples:**
264
265
```groovy
266
// Collection processing
267
def numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
268
269
// Find elements
270
def evens = numbers.findAll { it % 2 == 0 }
271
assert evens == [2, 4, 6, 8, 10]
272
273
def firstBig = numbers.find { it > 5 }
274
assert firstBig == 6
275
276
// Transform collections
277
def doubled = numbers.collect { it * 2 }
278
assert doubled == [2, 4, 6, 8, 10, 12, 14, 16, 18, 20]
279
280
// Aggregate operations
281
def total = numbers.sum()
282
assert total == 55
283
284
def product = numbers.inject(1) { acc, val -> acc * val }
285
assert product == 3628800 // 10!
286
287
// Grouping and sorting
288
def words = ['apple', 'banana', 'apricot', 'blueberry', 'cherry']
289
def byFirstLetter = words.groupBy { it[0] }
290
assert byFirstLetter.a == ['apple', 'apricot']
291
assert byFirstLetter.b == ['banana', 'blueberry']
292
293
def sorted = words.sort { it.length() }
294
assert sorted[0] == 'apple'
295
296
// String operations
297
def text = "hello world"
298
assert text.capitalize() == "Hello world"
299
assert text.padLeft(15) == " hello world"
300
assert text.center(15) == " hello world "
301
302
// Check if string is numeric
303
assert "123".isNumber()
304
assert !"abc".isNumber()
305
306
// String multiplication
307
assert "ha" * 3 == "hahaha"
308
309
// Number iteration
310
def result = []
311
5.times { result << it }
312
assert result == [0, 1, 2, 3, 4]
313
314
def countdown = []
315
5.downto(1) { countdown << it }
316
assert countdown == [5, 4, 3, 2, 1]
317
318
// Object utilities
319
def person = [name: 'John', age: 30]
320
person.with {
321
name = name.toUpperCase()
322
age += 1
323
}
324
assert person.name == 'JOHN'
325
assert person.age == 31
326
```
327
328
### Script Base Class
329
330
Base class for all Groovy scripts providing access to bindings and output methods.
331
332
```java { .api }
333
abstract class Script extends GroovyObjectSupport {
334
/**
335
* The main method that executes the script.
336
*/
337
public abstract Object run();
338
339
/**
340
* Gets the binding for this script.
341
*/
342
public Binding getBinding();
343
344
/**
345
* Sets the binding for this script.
346
*/
347
public void setBinding(Binding binding);
348
349
/**
350
* Prints a value to the output.
351
*/
352
public void print(Object value);
353
354
/**
355
* Prints a value with a newline to the output.
356
*/
357
public void println(Object value);
358
359
/**
360
* Printf-style formatted output.
361
*/
362
public void printf(String format, Object... values);
363
}
364
```
365
366
### Variable Binding
367
368
Container for script variables and their values.
369
370
```java { .api }
371
class Binding extends LinkedHashMap<String, Object> {
372
/**
373
* Creates an empty binding.
374
*/
375
Binding();
376
377
/**
378
* Creates a binding with the given variables.
379
*/
380
Binding(Map<String, Object> variables);
381
382
/**
383
* Gets the value of a variable.
384
*/
385
Object getVariable(String name);
386
387
/**
388
* Sets the value of a variable.
389
*/
390
void setVariable(String name, Object value);
391
392
/**
393
* Gets all variables as a map.
394
*/
395
Map<String, Object> getVariables();
396
397
/**
398
* Checks if a variable exists.
399
*/
400
boolean hasVariable(String name);
401
}
402
```
403
404
### Closures
405
406
Groovy's closure implementation providing functional programming capabilities.
407
408
```java { .api }
409
abstract class Closure<V> implements Cloneable, Runnable, GroovyCallable<V> {
410
/**
411
* Calls the closure with no arguments.
412
*/
413
V call();
414
415
/**
416
* Calls the closure with the given arguments.
417
*/
418
V call(Object... args);
419
420
/**
421
* Creates a curried version of this closure.
422
*/
423
Closure<V> curry(Object... args);
424
425
/**
426
* Creates a right-curried version of this closure.
427
*/
428
Closure<V> rcurry(Object... args);
429
430
/**
431
* Creates a memoized version of this closure.
432
*/
433
Closure<V> memoize();
434
435
/**
436
* Creates a trampoline version for tail recursion.
437
*/
438
TrampolineClosure<V> trampoline();
439
440
/**
441
* Composes this closure with another (this << other).
442
*/
443
Closure<V> leftShift(Closure<V> other);
444
445
/**
446
* Composes this closure with another (this >> other).
447
*/
448
Closure<V> rightShift(Closure<V> other);
449
450
/**
451
* Gets the owner of this closure.
452
*/
453
Object getOwner();
454
455
/**
456
* Gets the delegate of this closure.
457
*/
458
Object getDelegate();
459
460
/**
461
* Sets the delegate of this closure.
462
*/
463
void setDelegate(Object delegate);
464
465
/**
466
* Gets the resolve strategy for this closure.
467
*/
468
int getResolveStrategy();
469
470
/**
471
* Sets the resolve strategy for this closure.
472
*/
473
void setResolveStrategy(int resolveStrategy);
474
}
475
```
476
477
### String Interpolation
478
479
Groovy's interpolated string implementation.
480
481
```java { .api }
482
abstract class GString implements Comparable<Object>, CharSequence, Writable, Buildable {
483
/**
484
* Converts this GString to a String.
485
*/
486
String toString();
487
488
/**
489
* Gets the interpolated values.
490
*/
491
Object[] getValues();
492
493
/**
494
* Gets the string parts.
495
*/
496
String[] getStrings();
497
498
/**
499
* Gets the length of the string representation.
500
*/
501
int length();
502
503
/**
504
* Gets the character at the specified index.
505
*/
506
char charAt(int index);
507
508
/**
509
* Returns a subsequence of this GString.
510
*/
511
CharSequence subSequence(int start, int end);
512
}
513
```
514
515
### Ranges
516
517
Groovy's range implementations for numeric and object sequences.
518
519
```java { .api }
520
interface Range<T extends Comparable<T>> extends List<T> {
521
/**
522
* Gets the from value of this range.
523
*/
524
T getFrom();
525
526
/**
527
* Gets the to value of this range.
528
*/
529
T getTo();
530
531
/**
532
* Checks if this range contains the given value.
533
*/
534
boolean contains(Object obj);
535
536
/**
537
* Gets the size of this range.
538
*/
539
int size();
540
541
/**
542
* Creates a reversed range.
543
*/
544
List<T> reverse();
545
546
/**
547
* Steps through the range with the given step size.
548
*/
549
List<T> step(int step);
550
}
551
552
class IntRange implements Range<Integer> {
553
/**
554
* Creates an integer range.
555
*/
556
IntRange(int from, int to);
557
558
/**
559
* Gets the from value as an int.
560
*/
561
int getFromInt();
562
563
/**
564
* Gets the to value as an int.
565
*/
566
int getToInt();
567
568
/**
569
* Steps through the range with the given step.
570
*/
571
void step(int step, Closure closure);
572
}
573
574
class ObjectRange implements Range<Object> {
575
/**
576
* Creates an object range.
577
*/
578
ObjectRange(Comparable from, Comparable to);
579
580
/**
581
* Steps through the range with the given step.
582
*/
583
void step(int step, Closure closure);
584
}
585
```
586
587
### Tuples
588
589
Immutable sequence implementation for multiple return values.
590
591
```java { .api }
592
class Tuple implements List<Object> {
593
/**
594
* Creates a tuple from the given objects.
595
*/
596
Tuple(Object... objects);
597
598
/**
599
* Gets the element at the specified index.
600
*/
601
Object get(int index);
602
603
/**
604
* Gets the size of this tuple.
605
*/
606
int size();
607
608
/**
609
* Creates a sub-tuple.
610
*/
611
Tuple subTuple(int startIndex, int endIndex);
612
613
/**
614
* Converts to an array.
615
*/
616
Object[] toArray();
617
}
618
```
619
620
## Usage Examples
621
622
### Dynamic Script Execution
623
624
```java
625
import groovy.lang.GroovyShell;
626
import groovy.lang.Binding;
627
628
// Create shell with binding
629
Binding binding = new Binding();
630
binding.setVariable("x", 10);
631
binding.setVariable("y", 20);
632
633
GroovyShell shell = new GroovyShell(binding);
634
Object result = shell.evaluate("return x + y * 2");
635
System.out.println(result); // Prints: 50
636
```
637
638
### Meta-Programming with ExpandoMetaClass
639
640
```java
641
import groovy.lang.ExpandoMetaClass;
642
643
// Add method to String class
644
ExpandoMetaClass stringMeta = new ExpandoMetaClass(String.class, false);
645
stringMeta.defineProperty("reverse", new Closure<String>(null) {
646
public String doCall() {
647
return new StringBuilder((String)getDelegate()).reverse().toString();
648
}
649
});
650
stringMeta.initialize();
651
652
// Use the new method
653
String text = "hello";
654
String reversed = (String) stringMeta.getProperty(text, "reverse");
655
```
656
657
### Closure Usage
658
659
```java
660
import groovy.lang.Closure;
661
662
// Create and use a closure
663
Closure<String> greetClosure = new Closure<String>(null) {
664
public String doCall(Object name) {
665
return "Hello " + name + "!";
666
}
667
};
668
669
String greeting = greetClosure.call("World");
670
System.out.println(greeting); // Prints: Hello World!
671
672
// Curry the closure
673
Closure<String> helloJohn = greetClosure.curry("John");
674
System.out.println(helloJohn.call()); // Prints: Hello John!
675
```