Groovy Language Documentation
Groovy Language Documentation
Introduction
1.1. Syntax
1.1.1. Comments
1.1.2. Keywords
1.1.3. Identi ers
Normal identi ers
Quoted identi ers
1.1.4. Strings
String interpolation
Special case of interpolating closure expressions
Slashy string
Characters
1.1.5. Numbers
Integral literals
Alternative non-base 10 representations
Binary literal
Octal literal
Hexadecimal literal
Decimal literals
Underscore in literals
Number type su xes
Math operations
The case of the division operator
The case of the power operator
1.1.6. Booleans
1.1.7. Lists
1.1.8. Arrays
http://docs.groovy-lang.org/latest/html/documentation/ 1/502
1/6/2019 1.1.9. Maps Groovy Language Documentation
1.2. Operators
Precedence
Short-circuiting
1.2.4. Bitwise operators
Elvis operator
1.2.6. Object operators
Safe navigation operator
Direct eld access operator
Method pointer operator
Membership operator
Identity operator
Coercion operator
Diamond operator
Call operator
1.2.9. Operator precedence
Star import
Static import
Static import aliasing
Static star import
http://docs.groovy-lang.org/latest/html/documentation/ 2/502
1/6/2019 Import aliasing Groovy Language Documentation
1.4.1. Types
Primitive types
Class
Normal class
Inner class
Anonymous inner class
Abstract class
Interface
Constructors
Positional parameters
Named parameters
Methods
Method de nition
Named parameters
Mixing named and positional parameters
Default arguments
Varargs
Method selection algorithm
Exception declaration
Meta-annotations
Declaring meta-annotations
Behavior of meta-annotations
Meta-annotation parameters
Inheritance
Generics
1.4.2. Traits
Methods
Public methods
Abstract methods
http://docs.groovy-lang.org/latest/html/documentation/ 3/502
1/6/2019 Private methods Groovy Language Documentation
Final methods
The meaning of this
Interfaces
Properties
Fields
Private elds
Public elds
Composition of behaviors
Overriding default methods
Extending traits
Simple inheritance
Multiple inheritance
Chaining behavior
Self types
Type constraints on traits
1.5.1. Syntax
De ning a closure
Closures as an object
Calling a closure
1.5.2. Parameters
Normal parameters
Implicit parameter
Varargs
1.5.3. Delegation strategy
Delegate of a closure
Delegation strategy
Currying
Left currying
Right currying
Index based currying
Memoization
Composition
Trampoline
Method pointers
1.6. Semantics
1.6.1. Statements
Variable de nition
Variable assignment
Multiple assignment
Over ow and Under ow
Conditional structures
if / else
switch / case
Looping structures
Classic for loop
for in loop
while loop
Exception handling
Power assertion
Labeled statements
1.6.2. Expressions
GPath expressions
Object navigation
Expression Deconstruction
GPath for XML navigation
Number promotion
Closure to type coercion
Optional parentheses
Optional semicolons
Optional return keyword
Boolean expressions
Collections and Arrays
Matchers
Strings
Numbers
Object References
instanceof inference
Flow typing
Advanced type inference
Closures and type inference
@DelegatesTo
Static compilation
Dynamic vs static
The @CompileStatic annotation
Key bene ts
http://docs.groovy-lang.org/latest/html/documentation/ 6/502
1/6/2019 1.6.7. Type checking extensions Groovy Language Documentation
AST
Events
Working with extensions
Support classes
Class nodes
Helping the type checker
Throwing an error
isXXXExpression
Virtual methods
Scoping
2. Tools
2.1. Running Groovy from the commandline
2.1.1. groovy, the Groovy command
2.2. Compiling Groovy
Description
Required taskdef
<groovyc> Attributes
<groovyc> Nested Elements
Joint Compilation
2.2.3. Gant
2.2.4. Gradle
2.2.5. Maven integration
GMaven and GMavenPlus
GMaven
GMavenPlus
GMaven 2
Evaluation Result
Multi-line Expressions
De ne a Class
Use the Class
Variables
Functions
Commands
Recognized Commands
help
exit
import
grab
display
clear
show
inspect
purge
edit
load
save
record
history
alias
doc
set
Preferences
Recognized Preferences
interpreterMode
verbosity
colors
show-last-result
sanitize-stack-trace
editor
Setting a Preference
Listing Preferences
Clearing Preferences (i.e. Resetting to Defaults)
$HOME/.groovy/groovysh.rc
http://docs.groovy-lang.org/latest/html/documentation/ 8/502
1/6/2019 State Groovy Language Documentation
$HOME/.groovy/groovysh.history
Custom commands
Troubleshooting
Platform Problems
Problems loading the JLine DLL
Problems with Cygwin on Windows
2.3.2. GMavenPlus Maven Plugin
2.4.2. Basics
2.4.3. Features
Command-line Options and Arguments
Running Scripts
Editing Files
History and results
Interrupting a script
And more
2.4.4. Embedding the Console
2.4.5. Visualizing script output results
2.4.6. AST browser
Required taskdef
<groovydoc> Attributes
<groovydoc> Nested Elements
link
Example #1 - <groovydoc> Ant task
Example #2 - Executing <groovydoc> from Groovy
Custom templates
Stable
Snapshots
Prerequisites
Installation on Mac OS X
http://docs.groovy-lang.org/latest/html/documentation/ 9/502
1/6/2019 MacPorts Groovy Language Documentation
Homebrew
Installation on Windows
Other Distributions
Source Code
IDE plugin
3.1.5. Install Binary
3.2. Di erences with Java
3.2.8. GStrings
3.2.9. String and Character literals
3.2.10. Primitives and wrappers
3.2.11. Behaviour of ==
3.2.12. Conversions
Writing les
Traversing le trees
Data and objects
Duplicating elements
Maps
Map literals
Grouping
Ranges
Syntax enhancements for collections
GPath support
Spread operator
The star-dot `*.' operator
Property notation
Ranges, upto , and downto
3.4. Metaprogramming
3.4.1. Runtime metaprogramming
GroovyObject interface
invokeMethod
get/setProperty
get/setMetaClass
get/setAttribute
methodMissing
propertyMissing
static methodMissing
static propertyMissing
GroovyInterceptable
Categories
Metaclasses
The default metaclass MetaClassImpl
Custom metaclasses
Delegating metaclass
Magic package
http://docs.groovy-lang.org/latest/html/documentation/ 11/502
1/6/2019 Per instance metaclass Groovy Language Documentation
ExpandoMetaClass
Methods
Properties
Constructors
Static Methods
Borrowing Methods
Dynamic Method Names
Runtime Discovery
GroovyObject Methods
Overriding Static invokeMethod
Extending Interfaces
Extension modules
Instance methods
Static methods
Module descriptor
@groovy.transform.ToString
@groovy.transform.EqualsAndHashCode
@groovy.transform.TupleConstructor
Implementation Details
Immutability support
Customization options
@groovy.transform.MapConstructor
@groovy.transform.Canonical
@groovy.transform.InheritConstructors
@groovy.lang.Category
@groovy.transform.IndexedProperty
@groovy.lang.Lazy
@groovy.lang.Newify
@groovy.transform.Sortable
@groovy.transform.builder.Builder
@groovy.transform.AutoImplement
@groovy.transform.BaseScript
@groovy.lang.Delegate
@groovy.transform.Immutable
@groovy.transform.ImmutableBase
@groovy.transform.PropertyOptions
@groovy.transform.VisibilityOptions
@groovy.transform.ImmutableOptions
@groovy.transform.KnownImmutable
http://docs.groovy-lang.org/latest/html/documentation/ 12/502
1/6/2019 @groovy.transform.Memoized Groovy Language Documentation
@groovy.transform.TailRecursive
@groovy.lang.Singleton
@groovy.lang.Mixin
Logging improvements
@groovy.util.logging.Log
@groovy.util.logging.Commons
@groovy.util.logging.Log4j
@groovy.util.logging.Log4j2
@groovy.util.logging.Slf4j
Declarative concurrency
@groovy.transform.Synchronized
@groovy.transform.AutoExternalize
Safer scripting
@groovy.transform.ThreadInterrupt
@groovy.transform.TimedInterrupt
@groovy.transform.ConditionalInterrupt
Compiler directives
@groovy.transform.Field
@groovy.transform.PackageScope
@groovy.transform.AutoFinal
@groovy.transform.AnnotationCollector
@groovy.transform.TypeChecked
@groovy.transform.CompileStatic
@groovy.transform.CompileDynamic
@groovy.lang.DelegatesTo
@groovy.transform.SelfType
Swing patterns
@groovy.beans.Bindable
@groovy.beans.ListenerList
@groovy.beans.Vetoable
Test assistance
@groovy.transform.NotYetImplemented
@groovy.transform.ASTTest
Grape handling
@groovy.lang.Grab
@groovy.lang.GrabConfig
@groovy.lang.GrabExclude
@groovy.lang.GrabResolver
@groovy.lang.Grapes
ClassCodeExpressionTransformer
AST Nodes
Macros
Introduction
MacroClass
@Macro methods
Testing AST transformations
ASTTest
External references
JDBC Drivers
Logging
3.5.2. Detail
3.5.3. Usage
Annotation
grab(HashMap) Parameters
Arguments Map arguments
More Examples
3.6. Testing Guide
3.6.1. Introduction
Map Coercion
Closure Coercion
GDK Methods
Iterable#combinations
Iterable#eachCombination
Tool Support
Assertion Methods
shouldFail Methods
notYetImplemented Method
JUnit 4
JUnit 5
3.6.4. Testing with Spock
Speci cations
More Spock
3.6.5. Functional Tests with Geb
A Geb Script
More Geb
3.7. Processing JSON
3.7.1. JsonSlurper
Parser Variants
3.7.2. JsonOutput
Customizing Output
Formatted Output
Builders
Creating tables
Reading rows
Updating rows
Deleting rows
Using batches
Performing pagination
Fetching metadata
Stored procedures
3.8.5. Using DataSets
DOMCategory
3.9.2. GPath
MarkupBuilder
StreamingMarkupBuilder
MarkupBuilderHelper
DOMToGroovy
Adding nodes
Modifying / Removing nodes
Printing XML
XmlUtil
3.10. Scripting Ant tasks
<classpath>
<arg>
3.12.1. Introduction
3.12.2. Template framework
3.12.3. SimpleTemplateEngine
3.12.5. GStringTemplateEngine
3.12.6. XmlTemplateEngine
3.12.7. The MarkupTemplateEngine
Basics
Support methods
Includes
Fragments
Layouts
Rendering contents
Creation of a template engine
Automatic formatting
Automatic escaping
Common gotchas
GroovyShell
Multiple sources
Sharing data between a script and the application
GroovyClassLoader
GroovyScriptEngine
CompilationUnit
Passing in variables
3.15.5. @DelegatesTo
Explaining delegation strategy at compile time
@DelegatesTo
DelegatesTo modes
Simple delegation
Delegation strategy
Delegate to parameter
Multiple closures
Introduction
Import customizer
Import customizer
Inlining a customizer
Multiple customizers
Con g script ag
3.15.8. Builders
Creating a builder
BuilderSupport
FactoryBuilderSupport
Existing builders
MarkupBuilder
StreamingMarkupBuilder
SaxBuilder
StaxBuilder
DOMBuilder
NodeBuilder
JsonBuilder
StreamingJsonBuilder
SwingBuilder
AntBuilder
CliBuilder
ObjectGraphBuilder
JmxBuilder
FileTreeBuilder
3.16.1. Introduction
http://docs.groovy-lang.org/latest/html/documentation/ 18/502
1/6/2019 3.16.2. Monitoring the JVM Groovy Language Documentation
3.16.7. Troubleshooting
java.lang.SecurityException
3.16.8. JmxBuilder
Instantiating JmxBuilder
JMX Connectors
Connector Server
Connector Client
JmxBuilder.export() Syntax
Integration with GroovyMBean Class
JmxBuilder.bean() Syntax
Bean() Node - Specifying MBean ObjectName
Timer Export
Timer Period
Parameterless
Listener MBean
Emitter Syntax
Declare the Emitter
Broadcast Event
3.18. Security
3.19. Design patterns in Groovy
3.19.1. Patterns
Adapter Pattern
Delegation Example
Inheritance Example
Example
Composite Pattern
Example
Decorator Pattern
Traditional Example
Example
Iterator Pattern
Loan my Resource Pattern
Example
Example
Proxy Pattern
Example
Singleton Pattern
Example: The Classic Java Singleton
Spring Example
Further information
State Pattern
Example
Strategy Pattern
Example
Example
Visitor Pattern
Simple Example
Advanced Example
Why to use this
Make it Groovy
Summary
Further Information
3.19.2. References
4. Acknowledgements
4.1. Contributors
4.2. License
Introduction
Groovy…
builds upon the strengths of Java but has additional power features inspired by languages like Python, Ruby and Smalltalk
makes modern programming features available to Java developers with almost-zero learning curve
provides the ability to statically type check and statically compile your code for robustness and performance
supports Domain-Speci c Languages and other compact syntax so your code becomes easy to read and maintain
makes writing shell and build scripts easy with its powerful processing primitives, OO abilities and an Ant DSL
increases developer productivity by reducing sca olding code when developing web, GUI, database or console applications
http://docs.groovy-lang.org/latest/html/documentation/ 21/502
1/6/2019 simpli es testing by supporting unit testing and mocking out-of-the-box
Groovy Language Documentation
compiles straight to Java bytecode so you can use it anywhere you can use Java
1.1.1. Comments
Multiline comment
A multiline comment starts with /* and can be found at any position in the line. The characters following /* will be considered
part of the comment, including new line characters, up to the rst */ closing the comment. Multiline comments can thus be put
at the end of a statement, or even inside a statement.
GroovyDoc comment
Similarly to multiline comments, GroovyDoc comments are multiline, but start with /** and end with */ . Lines following the rst
GroovyDoc comment line can optionally start with a star * . Those comments are associated with:
methods de nitions
Although the compiler will not complain about GroovyDoc comments not being associated with the above language elements, you
should prepend those constructs with the comment right before it.
/**
* A Class description
*/
{
/** the name of the person */
name
/**
* Creates a greeting method for a certain person.
*
* @param otherPerson the person to greet
* @return a greeting message
*/
greet( otherPerson) {
"Hello ${otherPerson}"
}
}
GroovyDoc follows the same conventions as Java’s own JavaDoc. So you’ll be able to use the same tags as with JavaDoc.
http://docs.groovy-lang.org/latest/html/documentation/ 22/502
1/6/2019 Shebang line Groovy Language Documentation
Beside the single line comment, there is a special line comment, often called the shebang line understood by UNIX systems which
allows scripts to be run directly from the command-line, provided you have installed the Groovy distribution and the groovy
command is available on the PATH .
#!/usr/bin/env groovy
println "Hello from the shebang line"
The # character must be the rst character of the le. Any indentation would yield a compilation error.
1.1.2. Keywords
The following list represents all the keywords of the Groovy language:
Table 1. Keywords
while
'\u00C0' to '\u00D6'
'\u00D8' to '\u00F6'
'\u00F8' to '\u00FF'
'\u0100' to '\uFFFE'
Here are a few examples of valid identi ers (here, variable names):
name
item3
with_underscore
$dollarStart
http://docs.groovy-lang.org/latest/html/documentation/ 23/502
1/6/2019 Groovy Language Documentation
3tier
a+b
a#b
All keywords are also valid identi ers when following a dot:
foo.
foo.
foo.
foo.
foo.
map = [:]
As we shall see in the following section on strings, Groovy provides di erent string literals. All kind of strings are actually allowed
after the dot:
map.'single quote'
map."double quote"
map.'''triple single quote'''
map."""triple double quote"""
map./slashy /
map.$/dollar slashy /$
There’s a di erence between plain character strings and Groovy’s GStrings (interpolated strings), as in that the latter case, the
interpolated values are inserted in the nal string for evaluating the whole identi er:
firstname = "Homer"
map."Simpson-${firstname}" = "Homer Simpson"
1.1.4. Strings
Text literals are represented in the form of chain of characters called strings. Groovy lets you instantiate java.lang.String
objects, as well as GStrings ( groovy.lang.GString ) which are also called interpolated strings in other programming languages.
Single quoted strings are plain java.lang.String and don’t support interpolation.
String concatenation
All the Groovy strings can be concatenated with the + operator:
http://docs.groovy-lang.org/latest/html/documentation/ 24/502
1/6/2019 Groovy Language Documentation
'ab' == 'a' + 'b'
Triple single quoted strings are plain java.lang.String and don’t support interpolation.
Triple single quoted strings are multiline. You can span the content of the string across line boundaries without the need to split
the string in several pieces, without contatenation or newline escape characters:
If your code is indented, for example in the body of the method of a class, your string will contain the whitespace of the
indentation. The Groovy Development Kit contains methods for stripping out the indentation with the String#stripIndent()
method, and with the String#stripMargin() method that takes a delimiter character to identify the text to remove from the
beginning of a string.
startingAndEndingWithANewline = '''
line one
line two
line three
'''
You will notice that the resulting string contains a newline character as rst character. It is possible to strip that character by
escaping the newline with a backslash:
strippedFirstNewline = '''\
line one
line two
line three
'''
!strippedFirstNewline.startsWith('\n')
And you can escape the escape character itself with a double backslash:
'\t' tabulation
'\b' backspace
'\n' newline
http://docs.groovy-lang.org/latest/html/documentation/ 25/502
1/6/2019 Groovy Language Documentation
Escape sequence Character
'\f' formfeed
'\\' backslash
'\'' single quote (for single quoted and triple single quoted strings)
'\"' double quote (for double quoted and triple double quoted
strings)
Double quoted strings are plain java.lang.String if there’s no interpolated expression, but are
groovy.lang.GString instances if interpolation is present.
To escape a double quote, you can use the backslash character: "A double quote: \"".
String interpolation
Any Groovy expression can be interpolated in all string literals, apart from single and triple single quoted strings. Interpolation is
the act of replacing a placeholder in the string with its value upon evaluation of the string. The placeholder expressions are
surrounded by ${} or pre xed with $ for dotted expressions. The expression value inside the placeholder is evaluated to its
string representation when the GString is passed to a method taking a String as argument by calling toString() on that
expression.
But any Groovy expression is valid, as we can see in this example with an arithmetic expression:
Not only are expressions allowed in between the ${} placeholder, but so are statements. However, a statement’s
value is just null . So if several statements are inserted in that placeholder, the last one should somehow return
a meaningful value to be inserted. For instance, "The sum of 1 and 2 is equal to ${def a = 1; def b = 2; a + b}" is
supported and works as expected but a good practice is usually to stick to simple expressions inside GString
placeholders.
In addition to ${} placeholders, we can also use a lone $ sign pre xing a dotted expression:
http://docs.groovy-lang.org/latest/html/documentation/ 26/502
1/6/2019 Groovy Language Documentation
person = [name: 'Guillaume', age: 36]
"$person.name is $person.age years old" == 'Guillaume is 36 years old'
But only dotted expressions of the form a.b , a.b.c , etc, are valid, but expressions that would contain parentheses like method
calls, curly braces for closures, or arithmetic operators would be invalid. Given the following variable de nition of a number:
number = 3.14
The following statement will throw a groovy.lang.MissingPropertyException because Groovy believes you’re trying to access
the toString property of that number, which doesn’t exist:
shouldFail( ) {
println "$number.toString()"
}
If you need to escape the $ or ${} placeholders in a GString so they appear as is without interpolation, you just need to use a \
backslash character to escape the dollar sign:
'${name}' == "\${name}"
Here, the closure takes a single java.io.StringWriter argument, to which you can append content with the << leftShift
2
operator. In either case, both placeholders are embedded closures.
In appearance, it looks like a more verbose way of de ning expressions to be interpolated, but closures have an interesting
advantage over mere expressions: lazy evaluation.
number = 1 1
eagerGString = "value == ${number}"
lazyGString = "value == ${ -> number }"
number = 2 4
eagerGString == "value == 1" 5
We de ne a number variable containing 1 that we then interpolate within two GStrings, as an expression in
1
eagerGString and as a closure in lazyGString .
2 We expect the resulting string to contain the same string value of 1 for eagerGString .
3 Similarly for lazyGString
4 Then we change the value of the variable to a new number
http://docs.groovy-lang.org/latest/html/documentation/ 27/502
1/6/2019 5 With a plain interpolated expression, the value was Groovy
actuallyLanguage
bound atDocumentation
the time of creation of the GString.
But with a closure expression, the closure is called upon each coercion of the GString into String, resulting in an updated
6
string containing the new number value.
An embedded closure expression taking more than one parameter will generate an exception at runtime. Only
closures with zero or one parameters are allowed.
takeString( message) { 4
message 5
message
}
message 2
result = takeString(message) 3
result
result == 'The message is hello'
GString and Strings having di erent hashCode values, using GString as Map keys should be avoided, especially if we try to retrieve
an associated value with a String instead of a GString.
key = "a"
m = ["${key}": "letter ${key}"] 1
m["a"] == 2
http://docs.groovy-lang.org/latest/html/documentation/ 28/502
1/6/2019 Groovy Language Documentation
name = 'Groovy'
= """
Dear Mr ${name},
Yours sincerly,
Dave
"""
.toString().contains('Groovy')
Neither double quotes nor single quotes need be escaped in triple double quoted strings.
Slashy string
Beyond the usual quoted strings, Groovy o ers slashy strings, which use / as delimiters. Slashy strings are particularly useful for
de ning regular expressions and patterns, as there is no need to escape backslashes.
fooPattern = /.*foo.*/
fooPattern == '.*foo.*'
multilineSlashy = /one
two
three/
multilineSlashy.contains('\n')
color = 'blue'
interpolatedSlashy = /a ${color} car/
An empty slashy string cannot be represented with a double forward slash, as it’s understood by the Groovy parser as a line
comment. That’s why the following assert would actually not compile as it would look like a non-terminated statement:
'' == //
As slashy strings were mostly designed to make regexp easier so a few things that are errors in GStrings like $()
will work with slashy strings.
name = "Guillaume"
date = "April, 1st"
dollarSlashy = $/
$name,
today we're ${date}.
$ dollar sign
$$ escaped dollar sign
\ backslash
/ forward slash
$/ escaped forward slash
$$$/ escaped opening dollar slashy
$/$$ escaped closing dollar slashy
/$
assert [
' ',
' , 1st',
'$ dollar sign',
'$ escaped dollar sign',
'\\ backslash',
'/ forward slash',
'/ escaped forward slash',
'$/ escaped opening dollar slashy',
'/$ escaped closing dollar slashy'
].every { dollarSlashy.contains(it) }
Slashy /…/ \
Characters
Unlike Java, Groovy doesn’t have an explicit character literal. However, you can be explicit about making a Groovy string an actual
character, by three di erent means:
c1 = 'A' 1
c1
c2 = 'B' 2
c2
c3 = ( )'C' 3
c3
1 by being explicit when declaring a variable holding the character by specifying the char type
2 by using type coercion with the as operator
3 by using a cast to char operation
http://docs.groovy-lang.org/latest/html/documentation/ 30/502
1/6/2019 Groovy Language Documentation
The rst option 1 is interesting when the character is held in a variable, while the other two ( 2 and 3 ) are more
interesting when a char value must be passed as argument of a method call.
1.1.5. Numbers
Groovy supports di erent kinds of integral literals and decimal literals, backed by the usual Number types of Java.
Integral literals
The integral literal types are the same as in Java:
byte
char
short
int
long
java.lang.BigInteger
You can create integral numbers of those types with the following declarations:
// primitive types
b = 1
c = 2
s = 3
i = 4
l = 5
// infinite precision
bi = 6
If you use optional typing by using the def keyword, the type of the integral number will vary: it’ll adapt to the capacity of the
type that can hold that number.
a = 1
a
// Integer.MAX_VALUE
b = 2147483647
b
// Integer.MAX_VALUE + 1
c = 2147483648
c
// Long.MAX_VALUE
d = 9223372036854775807
d
// Long.MAX_VALUE + 1
e = 9223372036854775808
e
http://docs.groovy-lang.org/latest/html/documentation/ 31/502
1/6/2019 Groovy Language Documentation
na = -1
na
// Integer.MIN_VALUE
nb = -2147483648
nb
// Integer.MIN_VALUE - 1
nc = -2147483649
nc
// Long.MIN_VALUE
nd = -9223372036854775808
nd
// Long.MIN_VALUE - 1
ne = -9223372036854775809
ne
Binary literal
Binary numbers start with a 0b pre x:
xInt = 0b10101111
xInt == 175
xShort = 0b11001001
xShort == 201
xByte = 0b11
xByte == 3
xLong = 0b101101101101
xLong == 2925l
xBigInteger = 0b111100100001
xBigInteger == 3873g
xNegativeInt = -0b10101111
xNegativeInt == -175
Octal literal
Octal numbers are speci ed in the typical format of 0 followed by octal digits.
xInt = 077
xInt == 63
xShort = 011
xShort == 9
xByte = 032
xByte == 26
xLong = 0246
xLong == 166l
xBigInteger = 01111
xBigInteger == 585g
xNegativeInt = -077
xNegativeInt == -63
Hexadecimal literal
http://docs.groovy-lang.org/latest/html/documentation/ 32/502
1/6/2019 Hexadecimal numbers are speci ed in the typical format of 0x followed
Groovy LanguagebyDocumentation
hex digits.
xInt = 0x77
xInt == 119
xShort = 0xaa
xShort == 170
xByte = 0x3a
xByte == 58
xLong = 0xffff
xLong == 65535l
xBigInteger = 0xaaaa
xBigInteger == 43690g
xDouble = ('0x1.0p0')
xDouble == 1.0d
xNegativeInt = -0x77
xNegativeInt == -119
Decimal literals
The decimal literal types are the same as in Java:
float
double
java.lang.BigDecimal
You can create decimal numbers of those types with the following declarations:
// primitive types
f = 1.234
d = 2.345
// infinite precision
bd = 3.456
Decimals can use exponents, with the e or E exponent letter, followed by an optional sign, and a integral number representing
the exponent:
1e3 == 1_000.0
2E4 == 20_000.0
3e+1 == 30.0
4E-2 == 0.04
5e-1 == 0.5
Conveniently for exact decimal number calculations, Groovy choses java.lang.BigDecimal as its decimal number type. In
addition, both float and double are supported, but require an explicit type declaration, type coercion or su x. Even if
BigDecimal is the default for decimal numbers, such literals are accepted in methods or closures taking float or double as
parameter types.
Underscore in literals
When writing long literal numbers, it’s harder on the eye to gure out how some numbers are grouped together, for example with
groups of thousands, of words, etc. By allowing you to place underscore in number literals, it’s easier to spot those groups:
http://docs.groovy-lang.org/latest/html/documentation/ 33/502
1/6/2019 Groovy Language Documentation
creditCardNumber = 1234_5678_9012_3456L
socialSecurityNumbers = 999_99_9999L
monetaryAmount = 12_345_132.12
hexBytes = 0xFF_EC_DE_5E
hexWords = 0xFFEC_DE5E
maxLong = 0x7fff_ffff_ffff_ffffL
alsoMaxLong = 9_223_372_036_854_775_807L
bytes = 0b11010010_01101001_10010100_10010010
Type Su x
BigInteger G or g
Long L or l
Integer I or i
BigDecimal G or g
Double D or d
Float F or f
Examples:
42I == ('42')
42i == ('42') // lowercase i more readable
123L == ("123") // uppercase L more readable
2147483648 == ('2147483648') // Long type used, value too large for an Integer
456G == ('456')
456g == ('456')
123.45 == ('123.45') // default BigDecimal type used
1.200065D == ('1.200065')
1.234F == ('1.234')
1.23E23D == ('1.23E23')
0b1111L. == // binary
0xFFi. == // hexadecimal
034G. == // octal
Math operations
Although operators are covered later on, it’s important to discuss the behavior of math operations and what their resulting types
are.
binary operations between byte , char , short and int result in int
binary operations involving long with byte , char , short and int result in long
binary operations involving BigInteger and any other integral type result in BigInteger
binary operations involving BigDecimal with byte , char , short , int and BigInteger result in BigDecimal
http://docs.groovy-lang.org/latest/html/documentation/ 34/502
1/6/2019 Groovy Language Documentation
byte char short int long BigInteger oat double BigDecimal
byte int int int int long BigInteger double double BigDecimal
BigDecimal BigDecimal
Thanks to Groovy’s operator overloading, the usual arithmetic operators work as well with BigInteger and
BigDecimal , unlike in Java where you have to use explicit methods for operating on those numbers.
BigDecimal division is performed with the divide() method if the division is exact (i.e. yielding a result that can be
represented within the bounds of the same precision and scale), or using a MathContext with a precision
(http://docs.oracle.com/javase/7/docs/api/java/math/BigDecimal.html#precision()) of the maximum of the two operands' precision
plus an extra precision of 10, and a scale (http://docs.oracle.com/javase/7/docs/api/java/math/BigDecimal.html#scale()) of the
maximum of 10 and the maximum of the operands' scale.
For integer division like in Java, you should use the intdiv() method, as Groovy doesn’t provide a dedicated
integer division operator symbol.
The following rules are used by Groovy’s power operation to determine the resulting type:
if the exponent is strictly negative, then return an Integer , Long or Double if the result value ts in that type
if the base is an Integer , then return an Integer if the result value ts in it, otherwise a BigInteger
if the base is a Long , then return a Long if the result value ts in it, otherwise a BigInteger
http://docs.groovy-lang.org/latest/html/documentation/ 35/502
1/6/2019 Groovy Language Documentation
// base and exponent are ints and the result can be represented by an Integer
2 ** 3 // 8
10 ** 9 // 1_000_000_000
1.1.6. Booleans
Boolean is a special data type that is used to represent truth values: true and false . Use this data type for simple ags that
track true/false conditions.
Boolean values can be stored in variables, assigned into elds, just like any other data type:
myBooleanVariable =
untypedBooleanVar =
booleanField =
true and false are the only two primitive boolean values. But more complex boolean expressions can be represented using
logical operators.
In addition, Groovy has special rules (often referred to as Groovy Truth) for coercing non-boolean objects to a boolean value.
1.1.7. Lists
Groovy uses a comma-separated list of values, surrounded by square brackets, to denote lists. Groovy lists are plain JDK
java.util.List , as Groovy doesn’t de ne its own collection classes. The concrete list implementation used when de ning list
literals are java.util.ArrayList by default, unless you decide to specify otherwise, as we shall see later on.
numbers = [1, 2, 3] 1
numbers 2
numbers.size() == 3 3
1 We de ne a list numbers delimited by commas and surrounded by square brackets, and we assign that list into a variable
http://docs.groovy-lang.org/latest/html/documentation/ 36/502
1/6/2019 2 Groovy Language Documentation
The list is an instance of Java’s java.util.List interface
3 The size of the list can be queried with the size() method, and shows our list contains 3 elements
In the above example, we used a homogeneous list, but you can also create lists containing values of heterogeneous types:
We mentioned that by default, list literals are actually instances of java.util.ArrayList , but it is possible to use a di erent
backing type for our lists, thanks to using type coercion with the as operator, or with explicit type declaration for your variables:
arrayList = [1, 2, 3]
arrayList java.util.
linkedList = [2, 3, 4] 1
linkedList java.util.
otherLinked = [3, 4, 5] 2
otherLinked java.util.
You can access elements of the list with the [] subscript operator (both for reading and setting values) with positive indices or
negative indices to access elements from the end of the list, as well as with ranges, and use the << leftShift operator to append
elements to a list:
letters[0] == 'a' 1
letters[1] == 'b'
letters[-1] == 'd' 2
letters[-2] == 'c'
letters[2] = 'C' 3
letters[2] == 'C'
letters[ 4] == 'e'
letters[-1] == 'e'
As lists can be heterogeneous in nature, lists can also contain other lists to create multi-dimensional lists:
multi[1][0] == 2 2
1.1.8. Arrays
Groovy reuses the list notation for arrays, but to make such literals arrays, you need to explicitely de ne the type of the array
through coercion or type declaration.
arrStr [] 2
!(arrStr )
numArr = [1, 2, 3] [] 3
numArr [] 4
numArr.size() == 3
matrix3 = [3][3] 1
matrix3.size() == 3
[][] matrix2 2
names[2] = 'Blackdrag' 2
names[2] == 'Blackdrag'
Java’s array initializer notation is not supported by Groovy, as the curly braces can be misinterpreted with the
notation of Groovy closures.
1.1.9. Maps
Sometimes called dictionaries or associative arrays in other languages, Groovy features maps. Maps associate keys to values,
separating keys and values with colons, and each key/value pairs with commas, and the whole keys and values surrounded by
square brackets.
http://docs.groovy-lang.org/latest/html/documentation/ 38/502
1/6/2019 Groovy Language Documentation
colors = [red: '#FF0000', green: '#00FF00', blue: '#0000FF'] 1
colors['red'] == '#FF0000' 2
colors.green == '#00FF00' 3
colors['pink'] = '#FF00FF' 4
colors.yellow = '#FFFF00' 5
colors.pink == '#FF00FF'
colors['yellow'] == '#FFFF00'
colors java.util.
1 We de ne a map of string color names, associated with their hexadecimal-coded html colors
2 We use the subscript notation to check the content associated with the red key
3 We can also use the property notation to assert the color green’s hexadecimal representation
4 Similarly, we can use the subscript notation to add a new key/value pair
5 Or the property notation, to add the yellow color
When using names for the keys, we actually de ne string keys in the map.
colors.unknown ==
In the examples above, we used string keys, but you can also use values of other types as keys:
numbers[1] == 'one'
Here, we used numbers as keys, as numbers can unambiguously be recognized as numbers, so Groovy will not create a string key
like in our previous examples. But consider the case you want to pass a variable in lieu of the key, to have the value of that
variable become the key:
key = 'name'
person = [key: 'Guillaume'] 1
!person.containsKey('name') 2
person.containsKey('key') 3
The key associated with the 'Guillaume' name will actually be the "key" string, not the value associated with the key
1
variable
2 The map doesn’t contain the 'name' key
3 Instead, the map contains a 'key' key
You can also pass quoted strings as well as keys: ["name": "Guillaume"]. This is mandatory if your key string isn’t a
valid identi er, for example if you wanted to create a string key containing a hash like in: ["street-name": "Main
street"].
When you need to pass variable values as keys in your map de nitions, you must surround the variable or expression with
parentheses:
http://docs.groovy-lang.org/latest/html/documentation/ 39/502
1/6/2019 Groovy Language Documentation
person = [(key): 'Guillaume'] 1
person.containsKey('name') 2
!person.containsKey('key') 3
This time, we surround the key variable with parentheses, to instruct the parser we are passing a variable rather than
1
de ning a string key
2 The map does contain the name key
3 But the map doesn’t contain the key key as before
1.2. Operators
This chapter covers the operators of the Groovy programming language.
+ addition
- subtraction
* multiplication
% remainder
1 + 2 == 3
4 - 3 == 1
3 * 5 == 15
3 / 2 == 1.5
10 % 3 == 1
2 ** 3 == 8
Unary operators
The + and - operators are also available as unary operators:
+3 == 3
-4 == 0 - 4
-(-1) == 1 1
1 Note the usage of parentheses to surround an expression to apply the unary minus to that surrounded expression.
In terms of unary arithmetics operators, the ++ (increment) and -- (decrement) operators are available, both in pre x and
post x notation:
http://docs.groovy-lang.org/latest/html/documentation/ 40/502
1/6/2019 Groovy Language Documentation
a = 2
b = a++ * 3 1
a == 3 && b == 6
c = 3
d = c-- * 2 2
c == 2 && d == 6
e = 1
f = ++e + 3 3
e == 2 && f == 5
g = 4
h = --g + 1 4
g == 3 && h == 4
1 The post x increment will increment a after the expression has been evaluated and assigned into b
2 The post x decrement will decrement c after the expression has been evaluated and assigned into d
3 The pre x increment will increment e before the expression is evaluated and assigned into f
4 The pre x decrement will decrement g before the expression is evaluated and assigned into h
+=
-=
*=
/=
%=
**=
http://docs.groovy-lang.org/latest/html/documentation/ 41/502
1/6/2019 Groovy Language Documentation
a = 4
a += 3
a == 7
b = 5
b -= 3
b == 2
c = 5
c *= 3
c == 15
d = 10
d /= 2
d == 5
e = 10
e %= 3
e == 1
f = 3
f **= 2
f == 9
Operator Purpose
== equal
!= di erent
Here are some examples of simple number comparisons using these operators:
1 + 2 == 3
3 != 4
-2 < 3
2 <= 2
3 <= 4
5 > 1
5 >= -2
|| : logical "or"
! : logical "not"
! 1
&& 2
|| 3
Precedence
The logical "not" has a higher priority than the logical "and".
(! && ) == 1
Here, the assertion is true (as the expression in parentheses is false), because "not" has a higher precedence than "and", so
1 it only applies to the rst "false" term; otherwise, it would have applied to the result of the "and", turned it into true, and the
assertion would have failed
The logical "and" has a higher priority than the logical "or".
|| && 1
Here, the assertion is true, because "and" has a higher precedence than "or", therefore the "or" is executed last and returns
1 true, having one true argument; otherwise, the "and" would have executed last and returned false, having one false
argument, and the assertion would have failed
Short-circuiting
The logical || operator supports short-circuiting: if the left operand is true, it knows that the result will be true in any case, so it
won’t evaluate the right operand. The right operand will be evaluated only if the left operand is false.
Likewise for the logical && operator: if the left operand is false, it knows that the result will be false in any case, so it won’t
evaluate the right operand. The right operand will be evaluated only if the left operand is true.
checkIfCalled() { 1
called =
}
called =
|| checkIfCalled()
!called 2
called =
|| checkIfCalled()
called 3
called =
&& checkIfCalled()
!called 4
called =
&& checkIfCalled()
called 5
1 We create a function that sets the called ag to true whenever it’s called
http://docs.groovy-lang.org/latest/html/documentation/ 43/502
1/6/2019 Groovy
In the rst case, after resetting the called ag, we con Language
rm that Documentation
if the left operand to || is true, the function is not called, as
2
|| short-circuits the evaluation of the right operand
3 In the second case, the left operand is false and so the function is called, as indicated by the fact our ag is now true
4 Likewise for && , we con rm that the function is not called with a false left operand
5 But the function is called with a true left operand
| : bitwise "or"
~ : bitwise negation
a = 0b00101010
a == 42
b = 0b00001000
b == 8
(a & a) == a 1
(a & b) == b 2
(a | a) == a 3
(a | b) == a 4
mask = 0b11111111 5
1 bitwise and
2 bitwise and returns common bits
3 bitwise or
4 bitwise or returns all '1' bits
5 setting a mask to check only the last 8 bits
6 bitwise exclusive or on self returns 0
7 bitwise exclusive or
8 bitwise negation
It’s worth noting that the internal representation of primitive types follow the Java Language Speci cation
(http://docs.oracle.com/javase/specs/jls/se8/html/jls-4.html). In particular, primitive types are signed, meaning that for a bitwise
negation, it is always good to use a mask to retrieve only the necessary bits.
In Groovy, bitwise operators have the particularity of being overloadable, meaning that you can de ne the behavior of those
operators for any kind of object.
Not operator
The "not" operator is represented with an exclamation mark ( ! ) and inverts the result of the underlying boolean expression. In
particular, it is possible to combine the not operator with the Groovy truth:
(! ) == 1
(!'foo') == 2
(!'') == 3
Ternary operator
The ternary operator is a shortcut expression that is equivalent to an if/else branch assigning some value to a variable.
Instead of:
( != && .length()>0) {
result = 'Found'
} {
result = 'Not found'
}
The ternary operator is also compatible with the Groovy truth, so you can make it even simpler:
Elvis operator
The "Elvis operator" is a shortening of the ternary operator. One instance of where this is handy is for returning a 'sensible default'
value if an expression resolves to false -ish (as in Groovy truth). A simple example might look like this:
1 with the ternary operator, you have to repeat the value you want to assign
2 with the Elvis operator, the value, which is tested, is used if it is not false -ish
Usage of the Elvis operator reduces the verbosity of your code and reduces the risks of errors in case of refactorings, by removing
the need to duplicate the expression which is tested in both the condition and the positive return value.
name = person?.name 2
name == 3
http://docs.groovy-lang.org/latest/html/documentation/ 45/502
1/6/2019 Groovy Language Documentation
{
name 1
}
user = ('Bob')
user.name == 'Name: Bob' 3
The user.name call triggers a call to the property of the same name, that is to say, here, to the getter for name . If you want to
retrieve the eld instead of calling the getter, you can use the direct eld access operator:
user.@name == 'Bob' 1
fun = str.&toUpperCase 2
upper = fun() 3
upper == str.toUpperCase() 4
There are multiple advantages in using method pointers. First of all, the type of such a method pointer is a
groovy.lang.Closure , so it can be used in any place a closure would be used. In particular, it is suitable to convert an existing
method for the needs of the strategy pattern:
result = []
elements.each {
result << action(it)
}
result
}
describe( p) { 2
"$p.name is $p.age"
}
action = .&describe 3
list = [
(name: 'Bob', age: 42),
(name: 'Julia', age: 35)] 4
1 the transform method takes each element of the list and calls the action closure on them, returning a new list
2 we de ne a function that takes a Person and returns a String
3 we create a method pointer on that function
4 we create the list of elements we want to collect the descriptors
5 the method pointer can be used where a Closure was expected
http://docs.groovy-lang.org/latest/html/documentation/ 46/502
1/6/2019 Method pointers are bound by the receiver and a methodGroovy
name. Language
Arguments are resolved at runtime, meaning that if you have
Documentation
multiple methods with the same name, the syntax is not di erent, only resolution of the appropriate method to be called will be
done at runtime:
doSomething( x) { 2*x } 2
reference = .&doSomething 3
reference('foo') == 'FOO' 4
reference(123) == 246 5
Pattern operator
The pattern operator ( ~ ) provides a simple way to create a java.util.regex.Pattern instance:
p = ~/foo/
p
while in general, you nd the pattern operator with an expression in a slashy-string, it can be used with any kind of String in
Groovy:
p = ~'foo' 1
p = ~"foo" 2
p = ~$/dollar/slashy $ /$ 3
p = ~"${pattern}" 4
Find operator
Alternatively to building a pattern, you can directly use the nd operator =~ to build a java.util.regex.Matcher instance:
m 2
(!m) { 3
1 =~ creates a matcher against the text variable, using the pattern on the right hand side
2 the return type of =~ is a Matcher
3 equivalent to calling if (!m.find())
Since a Matcher coerces to a boolean by calling its find method, the =~ operator is consistent with the simple use of Perl’s
=~ operator, when it appears as a predicate (in if , while , etc.).
Match operator
The match operator ( ==~ ) is a slight variation of the nd operator, that does not return a Matcher but a boolean and requires a
strict match of the input string:
http://docs.groovy-lang.org/latest/html/documentation/ 47/502
1/6/2019 Groovy Language Documentation
m = text ==~ /match/ 1
m 2
(m) { 3
1 ==~ matches the subject with the regular expression, but match must be strict
2 the return type of ==~ is therefore a boolean
3 equivalent to calling if (text ==~ /match/)
Spread operator
The Spread-dot Operator ( *. ), often abbreviated to just Spread Operator, is used to invoke an action on all items of an aggregate
object. It is equivalent to calling the action on each item and collecting the result into a list:
{
make
model
}
cars = [
(make: 'Peugeot', model: '508'),
(make: 'Renault', model: 'Clio')] 1
makes = cars*.make 2
The expression cars*.make is equivalent to cars.collect{ it.make } . Groovy’s GPath notation allows a short-cut when the
referenced property isn’t a property of the containing list, in that case it is automatically spread. In the previously mentioned case,
the expression cars.make can be used, though retaining the explicit spread-dot operator is often recommended.
The spread operator is null-safe, meaning that if an element of the collection is null, it will return null instead of throwing a
NullPointerException :
cars = [
(make: 'Peugeot', model: '508'),
, 1
*.make == 3
The spread operator can be used on any class which implements the Iterable interface:
http://docs.groovy-lang.org/latest/html/documentation/ 48/502
1/6/2019 Groovy Language Documentation
{
id
name
}
< > {
components = [
(id: 1, name: 'Foo'),
(id: 2, name: 'Bar')]
@Override
< > iterator() {
components.iterator()
}
}
composite = ()
composite*.id == [1,2]
composite*.name == ['Foo','Bar']
Use multiple invocations of the spread-dot operator (here cars*.models*.name ) when working with aggregates of data
structures which themselves contain aggregates:
{
name
< > models
}
@Canonical
{
name
}
cars = [
(name: 'Peugeot',
models: [ ('408'), ('508')]),
(name: 'Renault',
models: [ ('Clio'), ('Captur')])
]
makes = cars*.name
makes == ['Peugeot', 'Renault']
models = cars*.models*.name
models == [['408', '508'], ['Clio', 'Captur']]
models.sum() == ['408', '508', 'Clio', 'Captur'] // flatten one level
models.flatten() == ['408', '508', 'Clio', 'Captur'] // flatten all levels (one in this
case)
Consider using the collectNested DGM method instead of the spread-dot operator for collections of collections:
{
make
model
}
cars = [
[
(make: 'Peugeot', model: '408'),
(make: 'Peugeot', model: '508')
], [
(make: 'Renault', model: 'Clio'),
(make: 'Renault', model: 'Captur')
]
]
models = cars.collectNested{ it.model }
models == [['408', '508'], ['Clio', 'Captur']]
http://docs.groovy-lang.org/latest/html/documentation/ 49/502
1/6/2019 Spreading method arguments Groovy Language Documentation
There may be situations when the arguments of a method call can be found in a list that you need to adapt to the method
arguments. In such situations, you can use the spread operator to call the method. For example, imagine you have the following
method signature:
( x, y, z) {
x*y+z
}
args = [4,5,6]
(*args) == 26
args = [4]
(*args,5,6) == 26
items = [4,5] 1
list = [1,2,3,*items,6] 2
list == [1,2,3,4,5,6] 3
1 items is a list
2 we want to insert the contents of the items list directly into list without having to call addAll
3 the contents of items has been inlined into list
m1 = [c:3, d:4] 1
The position of the spread map operator is relevant, like illustrated in the following example:
m1 = [c:3, d:4] 1
Range operator
Groovy supports the concept of ranges and provides a notation ( .. ) to create ranges of objects:
http://docs.groovy-lang.org/latest/html/documentation/ 50/502
1/6/2019 Groovy Language Documentation
range = 0..5 1
(0..5).collect() == [0, 1, 2, 3, 4, 5] 2
(0..<5).collect() == [0, 1, 2, 3, 4] 3
(0..5) 4
(0..5).size() == 6 5
Ranges implementation is lightweight, meaning that only the lower and upper bounds are stored. You can create a range from
any Comparable object that has next() and previous() methods to determine the next / previous item in the range. For
example, you can create a range of characters this way:
('a'..'d').collect() == ['a','b','c','d']
Spaceship operator
The spaceship operator ( <=> ) delegates to the compareTo method:
(1 <=> 1) == 0
(1 <=> 2) == -1
(2 <=> 1) == 1
('a' <=> 'z') == -1
Subscript operator
The subscript operator is a short hand notation for getAt or putAt , depending on whether you nd it on the left hand side or
the right hand side of an assignment:
list = [0,1,2,3,4]
list[2] == 2 1
list[2] = 4 2
list[0..2] == [0,1,4] 3
list[0..2] = [6,6,6] 4
list == [6,6,6,3,4] 5
The subscript operator, in combination with a custom implementation of getAt / putAt is a convenient way for destructuring
objects:
http://docs.groovy-lang.org/latest/html/documentation/ 51/502
1/6/2019 Groovy Language Documentation
{
id
name
getAt( i) { 1
(i) {
0: id
1: name
}
("No such element $i")
}
putAt( i, value) { 2
(i) {
0: id = value;
1: name = value;
}
("No such element $i")
}
}
user = (id: 1, name: 'Alex') 3
user[0] == 1 4
user[1] == 'Alex' 5
user[1] = 'Bob' 6
user.name == 'Bob' 7
Membership operator
The membership operator ( in ) is equivalent to calling the isCase method. In the context of a List , it is equivalent to calling
contains , like in the following example:
list = ['Grace','Rob','Emmy']
('Emmy' list) 1
Identity operator
In Groovy, using == to test equality is di erent from using the same operator in Java. In Groovy, it is calling equals . If you want
to compare reference equality, you should use is like in the following example:
list1 == list2 3
!list1. (list2) 4
Coercion operator
The coercion operator ( as ) is a variant of casting. Coercion converts object from one type to another without them being
compatible for assignment. Let’s take an example:
http://docs.groovy-lang.org/latest/html/documentation/ 52/502
1/6/2019 Groovy Language Documentation
x = 123
s = ( ) x 1
x = 123
s = x 1
When an object is coerced into another, unless the target type is the same as the source type, coercion will return a new object.
The rules of coercion di er depending on the source and target types, and coercion may fail if no conversion rules are found.
Custom conversion rules may be implemented thanks to the asType method:
{
name
}
{
id
name
asType( target) { 1
(target == ) {
(name: name)
}
("User cannot be coerced into $target")
}
}
u = (name: 'Xavier') 2
p = u 3
p 4
!(p ) 5
1 the User class de nes a custom conversion rule from User to Identifiable
2 we create an instance of User
3 we coerce the User instance into an Identifiable
4 the target is an instance of Identifiable
5 the target is not an instance of User anymore
Diamond operator
The diamond operator ( <> ) is a syntactic sugar only operator added to support compatibility with the operator of the same name
in Java 7. It is used to indicate that generic types should be inferred from the declaration:
In dynamic Groovy, this is totally unused. In statically type checked Groovy, it is also optional since the Groovy type checker
performs type inference whether this operator is present or not.
Call operator
The call operator () is used to call a method named call implicitly. For any object which de nes a call method, you can omit
the .call part and use the call operator instead:
http://docs.groovy-lang.org/latest/html/documentation/ 53/502
1/6/2019 Groovy Language Documentation
{
call( x) { 1
2*x
}
}
mc = ()
mc.call(2) == 4 2
mc(2) == 4 3
1 MyCallable de nes a method named call . Note that it doesn’t need to implement java.util.concurrent.Callable
2 we can call the method using the classic method call syntax
3 or we can omit .call thanks to the call operator
2 ** power
5 + - addition, subtraction
10 ^ binary/bitwise xor
11 | binary/bitwise or
13 || logical or
14 ? : ternary conditional
http://docs.groovy-lang.org/latest/html/documentation/ 54/502
1/6/2019 Groovy Language Documentation
Level Operator(s) Name(s)
?: elvis operator
{
size
plus( other) { 1
( .size + other.size)
}
}
Just by implementing the plus() method, the Bucket class can now be used with the + operator like so:
b1 = (4)
b2 = (11)
(b1 + b2).size == 15 1
1 The two Bucket objects can be added together with the + operator
All (non-comparator) Groovy operators have a corresponding method that you can implement in your own classes. The only
requirements are that your method is public, has the correct name, and has the correct number of arguments. The argument
types depend on what types you want to support on the right hand side of the operator. For example, you could support the
statement
(b1 + 11).size == 15
plus( capacity) {
( .size + capacity)
}
* a.multiply(b) a in b b.isCase(a)
| a.or(b) ++ a.next()
^ a.xor(b) +a a.positive()
as a.asType(b) -a a.negative()
To refer to some class Foo in the com.yoursite.com package you will need to use the fully quali ed name
com.yoursite.com.Foo , or else you can use an import statement as we’ll see below.
1.3.2. Imports
In order to refer to any class you need a quali ed reference to its package. Groovy follows Java’s notion of allowing import
statement to resolve class references.
For example, Groovy provides several builder classes, such as MarkupBuilder . MarkupBuilder is inside the package
groovy.xml so in order to use this class, you need to import it as shown:
xml !=
Default imports
Default imports are the imports that Groovy language provides by default. For example look at the following code:
()
The same code in Java needs an import statement to Date class like this: import java.util.Date. Groovy by default imports these
classes for you.
java.lang.*
java.util.*
java.io.*
java.net.*
groovy.lang.*
groovy.util.*
java.math.
java.math.
This is done because the classes from these packages are most commonly used. By importing these boilerplate code is reduced.
Simple import
http://docs.groovy-lang.org/latest/html/documentation/ 56/502
1/6/2019 A simple import is an import statement where you fully deGroovy
ne theLanguage
class name along with the package. For example the import
Documentation
statement import groovy.xml.MarkupBuilder in the code below is a simple import which directly refers to a class inside a package.
xml !=
Star import
Groovy, like Java, provides a special way to import all classes from a package using * , the so called star import. MarkupBuilder
is a class which is in package groovy.xml , alongside another class called StreamingMarkupBuilder . In case you need to use
both classes, you can do:
groovy.xml.
groovy.xml.
markupBuilder = ()
markupBuilder !=
() !=
That’s perfectly valid code. But with a * import, we can achieve the same e ect with just one line. The star imports all the classes
under package groovy.xml :
groovy.xml.*
markupBuilder = ()
markupBuilder !=
() !=
One problem with * imports is that they can clutter your local namespace. But with the kinds of aliasing provided by Groovy, this
can be solved easily.
Static import
Groovy’s static import capability allows you to reference imported classes as if they were static methods in your own class:
.FALSE
This is similar to Java’s static import capability but is a more dynamic than Java in that it allows you to de ne methods with the
same name as an imported method as long as you have di erent types:
java.lang. .format 1
format( i) { 2
i.toString()
}
main( [] args) {
format('String') == 'String' 3
().format( .valueOf(1)) == '1'
}
}
http://docs.groovy-lang.org/latest/html/documentation/ 57/502
1/6/2019 1 static import of method Groovy Language Documentation
2 declaration of method with same name as method statically imported above, but with a di erent parameter type
3 compile error in java, but is valid groovy code
If you have the same types, the imported class takes precedence.
.getInstance now
now(). == .getInstance().
For example, lets say we need to calculate sines and cosines for our application. The class java.lang.Math has static methods
named sin and cos which t our need. With the help of a static star import, we can do:
java.lang. .*
sin(0) == 0.0
cos(0) == 1.0
As you can see, we were able to access the methods sin and cos directly, without the Math. pre x.
Import aliasing
With type aliasing, we can refer to a fully quali ed class name using a name of our choice. This can be done with the as keyword,
as before.
For example we can import java.sql.Date as SQLDate and use it in the same le as java.util.Date without having to use
the fully quali ed name of either class:
java.util.
java.sql.
utilDate = (1000L)
sqlDate = (1000L)
utilDate java.util.
sqlDate java.sql.
Main.groovy
{ 1
}
}
This is typical code that you would nd coming from Java, where code has to be embedded into a class to be executable. Groovy
makes it easier, the following code is equivalent:
Main.groovy
A script can be considered as a class without needing to declare it, with some di erences.
Script class
A script (http://docs.groovy-lang.org/2.5.5/html/gapi/index.html?groovy/lang/Script.html) is always compiled into a class. The
Groovy compiler will compile the class for you, with the body of the script copied into a run method. The previous example is
therefore compiled as if it was the following:
Main.groovy
org.codehaus.groovy.runtime.
{ 1
run() { 2
}
main( [] args) { 4
.runScript( , args) 5
}
}
If the script is in a le, then the base name of the le is used to determine the name of the generated script class. In this example,
if the name of the le is Main.groovy , then the script class is going to be Main .
Methods
It is possible to de ne methods into a script, as illustrated here:
fib( n) {
n < 2 ? 1 : fib(n-1) + fib(n-2)
}
fib(10)==89
You can also mix methods and code. The generated script class will carry all methods into the script class, and assemble all script
bodies into the run method:
println 'Hello' 1
power( n) { 2**n } 2
println "2^6==${power(6)}" 3
1 script begins
2 a method is de ned within the script body
3 and script continues
run() {
println 'Hello' 2
println "2^6==${power(6)}" 3
}
main( [] args) {
.runScript( , args)
}
}
Even if Groovy creates a class from your script, it is totally transparent for the user. In particular, scripts are
compiled to bytecode, and line numbers are preserved. This implies that if an exception is thrown in a script, the
stack trace will show line numbers corresponding to the original script, not the generated code that we have
shown.
Variables
Variables in a script do not require a type de nition. This means that this script:
x = 1
y = 2
x+y == 3
x = 1
y = 2
x+y == 3
if the variable is declared as in the rst example, it is a local variable. It will be declared in the run method that the compiler
will generate and will not be visible outside of the script main body. In particular, such a variable will not be visible in other
methods of the script
If you want a variable to become a eld of the class without going into the Binding , you can use the @Field
annotation.
1.4.1. Types
Primitive types
Groovy supports the same primitive types as those de ned by the Java Language Speci cation
(http://docs.oracle.com/javase/specs/jls/se8/html/):
integral types: byte (8 bit), short (16 bit), int (32 bit) and long (64 bit)
char type (16 bit, usable as a numeric type, representing an UTF-16 code)
While Groovy declares and stores primitive elds and variables as primitives, because it uses Objects for everything, it autowraps
references to primitives. Just like Java, the wrappers it uses are
boolean Boolean
char Character
short Short
int Integer
long Long
oat Float
double Double
{
i
}
. .getDeclaredField('i').type == .
.i. != . && .i. == .
Now you may be concerned that this means every time you use a mathematical operator on a reference to a primitive that you’ll
incur the cost of unboxing and reboxing the primitive. But this is not the case, as Groovy will compile your operators into their
method equivalents (core-operators.html#_operator-overloading) and uses those instead. Additionally, Groovy will automatically
unbox to a primitive when calling a Java method that takes a primitive parameter and automatically box primitive method return
values from Java. However, be aware there are some di erences (core-di erences-java.html#_primitives_and_wrappers) from
Java’s method resolution.
Class
Groovy classes are very similar to Java classes, and are compatible with Java ones at JVM level. They may have methods, elds and
properties (think JavaBean properties but with less boilerplate). Classes and class members can have the same modi ers (public,
protected, private, static, etc) as in Java with some minor di erences at the source level which are explained shortly.
The key di erences between Groovy classes and their Java counterparts are:
Classes or methods with no visibility modi er are automatically public (a special annotation can be used to achieve package
private visibility).
Fields with no visibility modi er are turned into properties automatically, which results in less verbose code, since explicit
getter and setter methods aren’t needed. More on this aspect will be covered in the elds and properties section.
Classes do not need to have the same base name as their source le de nitions but it is highly recommended in most
scenarios (see also the next point about scripts).
One source le may contain one or more classes (but if a le contains any code not in a class, it is considered a script). Scripts
are just classes with some special conventions and will have the same name as their source le (so don’t include a class
de nition within a script having the same name as the script source le).
http://docs.groovy-lang.org/latest/html/documentation/ 61/502
1/6/2019 Groovy Language Documentation
{ 1
name 2
age
increaseAge( years) { 3
.age += years
}
}
Normal class
Normal classes refer to classes which are top level and concrete. This means they can be instantiated without restrictions from
any other classes or scripts. This way, they can only be public (even though the public keyword may be suppressed). Classes are
instantiated by calling their constructors, using the new keyword, as in the following snippet.
p = ()
Inner class
Inner classes are de ned within another classes. The enclosing class can use the inner class as usual. On the other side, a inner
class can access members of its enclosing class, even if they are private. Classes other than the enclosing class are not allowed to
access inner classes. Here is an example:
{
privateStr
callInnerMethod() {
().methodA() 1
{ 2
methodA() {
println "${privateStr}." 3
}
}
}
They increase encapsulation by hiding the inner class from other classes, which do not need to know about it. This also leads
to cleaner packages and workspaces.
They provide a good organization, by grouping classes that are used by only one class.
They lead to more maintainable codes, since inner classes are near the classes that use them.
In several cases, inner classes are implementation of interfaces whose methods are needed by the outer class. The code below
illustrates this with the usage of threads, which are very common.
http://docs.groovy-lang.org/latest/html/documentation/ 62/502
1/6/2019 Groovy Language Documentation
{
privateStr = 'some string'
startThread() {
( ()).start()
}
{
run() {
println "${privateStr}."
}
}
}
Note that the class Inner2 is de ned only to provide an implementation of the method run to class Outer2 . Anonymous inner
classes help to eliminate verbosity in this case.
{
privateStr = 'some string'
startThread() {
( () { 1
run() {
println "${privateStr}."
}
}).start() 2
}
}
comparing with the last example of previous section, the new Inner2() was replaced by new Runnable() along with all
1
its implementation
2 the method start is invoked normally
Abstract class
Abstract classes represent generic concepts, thus, they cannot be instantiated, being created to be subclassed. Their members
include elds/properties and abstract or concrete methods. Abstract methods do not have implementation, and must be
implemented by concrete subclasses.
{ 1
name
abstractMethod() 2
concreteMethod() {
println 'concrete'
}
}
Abstract classes are commonly compared to interfaces. But there are at least two important di erences of choosing one or
another. First, while abstract classes may contain elds/properties and concrete methods, interfaces may contain only abstract
methods (method signatures). Moreover, one class can implement several interfaces, whereas it can extend just one class,
abstract or not.
Interface
http://docs.groovy-lang.org/latest/html/documentation/ 63/502
1/6/2019 An interface de nes a contract that a class needs to conform to. An
Groovy interface
Language only de nes a list of methods that need to be
Documentation
implemented, but does not de ne the methods implementation.
{ 1
greet( name) 2
Methods of an interface are always public. It is an error to use protected or private methods in interfaces:
{
greet( name) 1
A class implements an interface if it de nes the interface in its implements list or if any of its superclasses does:
{ 1
greet( name) { 2
greeter = ()
greeter 3
1 The SystemGreeter declares the Greeter interface using the implements keyword
2 Then implements the required greet method
3 Any instance of SystemGreeter is also an instance of the Greeter interface
{ 1
sayBye( name)
}
1 the ExtendedGreeter interface extends the Greeter interface using the extends keyword
It is worth noting that for a class to be an instance of an interface, it has to be explicit. For example, the following class de nes the
greet method as it is declared in the Greeter interface, but does not declare Greeter in its interfaces:
{
greet( name) { println "Hello" }
}
greeter = ()
!(greeter )
In other words, Groovy does not de ne structural typing. It is however possible to make an instance of an object implement an
interface at runtime, using the as coercion operator:
greeter = () 1
coerced = greeter 2
coerced 3
You can see that there are two distinct objects: one is the source object, a DefaultGreeter instance, which does not implement
the interface. The other is an instance of Greeter that delegates to the coerced object.
Groovy interfaces do not support default implementation like Java 8 interfaces. If you are looking for something
similar (but not equal), traits are close to interfaces, but allow default implementation as well as other important
features described in this manual.
Constructors
Constructors are special methods used to initialize an object with a speci c state. As with normal methods, it is possible for a class
to declare more than one constructor, so long as each constructor has a unique type signature. If an object doesn’t require any
parameters during construction, it may use a no-arg constructor. If no constructors are supplied, an empty no-arg constructor will
be provided by the Groovy compiler.
positional parameters are used in a similar to how you would use Java constructors
named parameters allow you to specify parameter names when invoking the constructor.
Positional parameters
To create an object by using positional parameters, the respective class needs to declare one or more constructors. In the case of
multiple constructors, each must have a unique type signature. The constructors can also added to the class using the
groovy.transform.TupleConstructor (http://docs.groovy-lang.org/2.5.5/html/gapi/index.html?
groovy/transform/TupleConstructor.html) annotation.
Typically, once at least one constructor is declared, the class can only be instantiated by having one of its constructors called. It is
worth noting that, in this case, you can’t normally create the class with named parameters. Groovy does support named
parameters so long as the class contains a no-arg constructor or provides a constructor which takes a Map argument as the rst
(and potentially only) argument - see the next section for details.
There are three forms of using a declared constructor. The rst one is the normal Java way, with the new keyword. The others rely
on coercion of lists into the desired types. In this case, it is possible to coerce with the as keyword and by statically typing the
variable.
{
name
age
(name, age) { 1
.name = name
.age = age
}
}
person1 = ('Marie', 1) 2
person2 = ['Marie', 2] 3
person3 = ['Marie', 3] 4
1 Constructor declaration
2 Constructor invocation, classic Java way
3 Constructor usage, using coercion with as keyword
4 Constructor usage, using coercion in assignment
Named parameters
If no (or a no-arg) constructor is declared, it is possible to create objects by passing parameters in the form of a map
(property/value pairs). This can be in handy in cases where one wants to allow several combinations of parameters. Otherwise, by
using traditional positional parameters it would be necessary to declare all possible constructors. Having a constructor where the
http://docs.groovy-lang.org/latest/html/documentation/ 65/502
1/6/2019 rst (and perhaps only) argument is a Map argument is also supported
Groovy - such
Language a constructor may also be added using the
Documentation
groovy.transform.MapConstructor (http://docs.groovy-lang.org/2.5.5/html/gapi/index.html?
groovy/transform/MapConstructor.html) annotation.
{ 1
name
age
}
person4 = () 2
person6 = (age: 1) 4
1 No constructor declared
2 No parameters given in the instantiation
3 name parameter given in the instantiation
4 age parameter given in the instantiation
5 name and age parameters given in the instantiation
It is important to highlight, however, that this approach gives more power to the constructor caller, while imposing an increased
responsibility on the caller to get the names and value types correct. Thus, if greater control is desired, declaring constructors
using positional parameters might be preferred.
Notes:
While the example above supplied no constructor, you can also supply a no-arg constructor or a constructor where the rst
argument is a Map , most typically it’s the only argument.
When no (or a no-arg) constructor is declared, Groovy replaces the named constructor call by a call to the no-arg constructor
followed by calls to the setter for each supplied named property.
When the rst argument is a Map, Groovy combines all named parameters into a Map (regardless of ordering) and supplies the
map as the rst parameter. This can be a good approach if your properties are declared as final (since they will be set in the
constructor rather than after the fact with setters).
You can support both named and positional construction by supply both positional constructors as well as a no-arg or Map
constructor.
You can support hybrid construction by having a constructor where the rst argument is a Map but there are also additional
positional parameters. Use this style with caution.
Methods
Groovy methods are quite similar to other languages. Some peculiarities will be shown in the next subsections.
Method de nition
A method is de ned with a return type or with the def keyword, to make the return type untyped. A method can also receive any
number of arguments, which may not have their types explicitly declared. Java modi ers can be used normally, and if no visibility
modi er is provided, the method is public.
Methods in Groovy always return some value. If no return statement is provided, the value evaluated in the last line executed
will be returned. For instance, note that none of the following methods uses the return keyword.
If we don’t have the Map as the rst argument, then a Map must be supplied for that argument instead of named parameters.
Failure to do so will lead to groovy.lang.MissingMethodException :
Above exception can be avoided if we replace named arguments with an explicit Map argument:
Although Groovy allows you to mix named and positional parameters, it can lead to unnecessary confusion. Mix
named and positional arguments with caution.
Default arguments
Default arguments make parameters optional. If the argument is not supplied, the method assumes a default value.
Note that no mandatory parameter can be de ned after a default parameter is present, only other default parameters.
Varargs
Groovy supports methods with a variable number of arguments. They are de ned like this: def foo(p1, …, pn, T… args) .
Here foo supports n arguments by default, but also an unspeci ed number of further arguments exceeding n .
http://docs.groovy-lang.org/latest/html/documentation/ 67/502
1/6/2019 This example de nes a method foo , that can take any number
Groovyof arguments,
Language including no arguments at all. args.length will
Documentation
return the number of arguments given. Groovy allows T[] as a alternative notation to T… . That means any method with an array
as last parameter is seen by Groovy as a method that can take a variable number of arguments.
If a method with varargs is called with null as the vararg parameter, then the argument will be null and not an array of length
one with null as the only element.
If a varargs method is called with an array as an argument, then the argument will be that array instead of an array of length one
containing the given array as the only element.
Another important point are varargs in combination with method overloading. In case of method overloading Groovy will select
the most speci c method. For example if a method foo takes a varargs argument of type T and another method foo also takes
one argument of type T , the second method is preferred.
Exception declaration
Groovy automatically allows you to treat checked exceptions like unchecked exceptions. This means that you don’t need to
declare any checked exceptions that a method may throw as shown in the following example which can throw a
FileNotFoundException if the le isn’t found:
badRead() {
('doesNotExist.txt').text
}
shouldFail( ) {
badRead()
}
Nor will you be required to surround the call to the badRead method in the previous example within a try/catch block - though
you are free to do so if you wish.
If you wish to declare any exceptions that your code might throw (checked or otherwise) you are free to do so. Adding exceptions
won’t change how the code is used from any other Groovy code but can be seen as documentation for the human reader of your
code. The exceptions will become part of the method declaration in the bytecode, so if your code might be called from Java, it
might be useful to include them. Using an explicit checked exception declaration is illustrated in the following example:
http://docs.groovy-lang.org/latest/html/documentation/ 68/502
1/6/2019 Groovy Language Documentation
badRead() {
('doesNotExist.txt').text
}
shouldFail( ) {
badRead()
}
Fields
A eld is a member of a class or a trait which has:
an optional type
a mandatory name
{
id 1
description 2
DEBUG = 3
{
id = . () 1
// ...
}
It is possible to omit the type declaration of a eld. This is however considered a bad practice and in general it is a good idea to
use strong typing for elds:
{
mapping 1
}
{
< , > mapping 2
The di erence between the two is important if you want to use optional type checking later. It is also important for
documentation. However in some cases like scripting or if you want to rely on duck typing it may be interesting to omit the type.
Properties
A property is an externally visible feature of a class. Rather than just using a public eld to represent such features (which
provides a more limited abstraction and would restrict refactoring possibilities), the typical convention in Java is to follow JavaBean
conventions, i.e. represent the property using a combination of a private backing eld and getters/setters. Groovy follows these
same conventions but provides a simpler approach to de ning the property. You can de ne a property with:
an optional type
a mandatory name
{
name 1
age 2
1 creates a backing private String name eld, a getName and a setName method
2 creates a backing private int age eld, a getAge and a setAge method
{
name 1
age 2
( name, age) {
.name = name 3
.age = age 4
}
}
Properties are accessed by name and will call the getter or setter transparently, unless the code is in the class which de nes the
property:
{
name
name( name) {
.name = "Wonder$name" 1
}
wonder() {
.name 2
}
}
p = ()
p.name = 'Marge' 3
p.name == 'Marge' 4
p.name('Marge') 5
p.wonder() == 'WonderMarge' 6
1 this.name will directly access the eld because the property is accessed from within the class that de nes it
2 similarily a read access is done directly on the name eld
3 write access to the property is done outside of the Person class so it will implicitly call setName
4 read access to the property is done outside of the Person class so it will implicitly call getName
5 this will call the name method on Person which performs a direct access to the eld
6 this will call the wonder method on Person which performs a direct read access to the eld
It is worth noting that this behavior of accessing the backing eld directly is done in order to prevent a stack over ow when using
the property access syntax within a class that de nes the property.
It is possible to list the properties of a class thanks to the meta properties eld of an instance:
http://docs.groovy-lang.org/latest/html/documentation/ 70/502
1/6/2019 Groovy Language Documentation
{
name
age
}
p = ()
p.properties.keySet().containsAll(['name','age'])
By convention, Groovy will recognize properties even if there is no backing eld provided there are getters or setters that follow
the Java Beans speci cation. For example:
{
// a pseudo property "name"
setName( name) {}
getName() {}
p.age == 42 2
p.groovy = 3
Annotation
Annotation de nition
An annotation is a kind of special interface dedicated at annotating elements of the code. An annotation is a type which
superinterface is the Annotation (http://docs.oracle.com/javase/8/docs/api/index.html?java/lang/annotation/Annotation.html)
interface. Annotations are declared in a very similar way to interfaces, using the @interface keyword:
@interface {}
An annotation may de ne members in the form of methods without bodies and an optional default value. The possible member
types are limited to:
primitive types
Strings (http://docs.oracle.com/javase/8/docs/api/index.html?java/lang/String.html)
Classes (http://docs.oracle.com/javase/8/docs/api/index.html?java/lang/Class.html)
an enumeration (http://docs.oracle.com/javase/8/docs/api/index.html?java/lang/Enum.html)
For example:
http://docs.groovy-lang.org/latest/html/documentation/ 71/502
1/6/2019 Groovy Language Documentation
@interface {
value() 1
}
@interface {
value() 'something' 2
}
@interface {
step() 3
}
@interface {
appliesTo() 4
}
@interface {}
@interface {
[] value() 5
}
{ mon, tue, wed, thu, fri, sat, sun }
@interface {
dayOfWeek() 6
Unlike in the Java language, in Groovy, an annotation can be used to alter the semantics of the language. It is especially true of AST
transformations which will generate code based on annotations.
Annotation placement
An annotation can be applied on various elements of the code:
@SomeAnnotation 1
someMethod() {
// ...
}
@SomeAnnotation 2
{}
@SomeAnnotation 3
In order to limit the scope where an annotation can be applied, it is necessary to declare it on the annotation de nition, using the
Target (http://docs.oracle.com/javase/8/docs/api/index.html?java/lang/annotation/Target.html) annotation. For example, here is
how you would declare that an annotation can be applied to a class or a method:
java.lang.annotation.
java.lang.annotation.
@interface {} 2
@interface {
statusCode()
}
@Page(statusCode=404)
notFound() {
// ...
}
However it is possible to omit value= in the declaration of the value of an annotation if the member value is the only one being
set:
@interface {
value()
statusCode() 200
}
@Page(value='/home') 1
home() {
// ...
}
@Page('/users') 2
userList() {
// ...
}
@Page(value='error',statusCode=404) 3
notFound() {
// ...
}
1 we can omit the statusCode because it has a default value, but value needs to be set
2 since value is the only mandatory member without a default, we can omit value=
3 if both value and statusCode need to be set, it is required to use value= for the default value member
Retention policy
The visibility of an annotation depends on its retention policy. The retention policy of an annotation is set using the Retention
(http://docs.oracle.com/javase/8/docs/api/index.html?java/lang/annotation/Retention.html) annotation:
java.lang.annotation.
java.lang.annotation.
@Retention( .SOURCE) 1
@interface {} 2
http://docs.groovy-lang.org/latest/html/documentation/ 73/502
1/6/2019 The list of possible retention targets and description is available
Groovyin the RetentionPolicy
Language Documentation
(http://docs.oracle.com/javase/8/docs/api/index.html?java/lang/annotation/RetentionPolicy.html) enumeration. The choice usually
depends on whether you want an annotation to be visible at compile time or runtime.
{
result = []
alwaysExecuted() {
result << 1
}
@OnlyIf({ jdk>=6 })
supportedOnlyInJDK6() {
result << 'JDK 6'
}
@OnlyIf({ jdk>=7 && windows })
requiresJDK7AndWindows() {
result << 'JDK 7 Windows'
}
}
For the @OnlyIf annotation to accept a Closure as an argument, you only have to declare the value as a Class :
@Retention( .RUNTIME)
@interface {
value() 1
To complete the example, let’s write a sample runner that would use that information:
{
<T> T run( <T> taskClass) {
tasks = taskClass.newInstance() 1
= [jdk:6, windows: ] 2
onlyIf = m.getAnnotation( ) 5
(onlyIf) {
cl = onlyIf.value().newInstance(tasks,tasks) 6
cl. = 7
(cl()) { 8
m.invoke(tasks) 9
}
} {
m.invoke(tasks) 10
}
}
}
tasks 11
}
}
1 create a new instance of the class passed as an argument (the task class)
2 emulate an environment which is JDK 6 and not Windows
3 iterate on all declared methods of the task class
4 if the method is public and takes no-argument
5 try to nd the @OnlyIf annotation
6 if it is found get the value and create a new Closure out of it
http://docs.groovy-lang.org/latest/html/documentation/ 74/502
1/6/2019 7 Groovy
set the delegate of the closure to our environment Language Documentation
variable
8 call the closure, which is the annotation closure. It will return a boolean
9 if it is true , call the method
10 if the method is not annotated with @OnlyIf , execute the method anyway
11 after that, return the task object
tasks = .run( )
tasks.result == [1, 'JDK 6']
Meta-annotations
Declaring meta-annotations
Meta-annotations, also known as annotation aliases are annotations that are replaced at compile time by other annotations (one
meta-annotation is an alias for one or more annotations). Meta-annotations can be used to reduce the size of code involving
multiple annotations.
Let’s start with a simple example. Imagine you have the @Service and @Transactional annotations and that you want to
annotate a class with both:
@Service
@Transactional
{}
Given the multiplication of annotations that you could add to the same class, a meta-annotation could help by reducing the two
annotations with a single one having the very same semantics. For example, we might want to write this instead:
@TransactionalService 1
{}
1 @TransactionalService is a meta-annotation
A meta-annotation is declared as a regular annotation but annotated with @AnnotationCollector and the list of annotations it
is collecting. In our case, the @TransactionalService annotation can be written:
groovy.transform.
@Service 1
@Transactional 2
@AnnotationCollector 3
@interface {
}
Behavior of meta-annotations
Groovy supports both precompiled and source form meta-annotations. This means that your meta-annotation may be
precompiled, or you can have it in the same source tree as the one you are currently compiling.
INFO: Meta-annotations are a Groovy-only feature. There is no chance for you to annotate a Java class with a meta-annotation and
hope it will do the same as in Groovy. Likewise, you cannot write a meta-annotation in Java: both the meta-annotation
de nition and usage have to be Groovy code. But you can happily collect Java annotations and Groovy annotations within your
meta-annotation.
When the Groovy compiler encounters a class annotated with a meta-annotation, it replaces it with the collected annotations. So,
in our previous example, it will replace @TransactionalService with @Transactional and @Service :
http://docs.groovy-lang.org/latest/html/documentation/ 75/502
1/6/2019 Groovy Language Documentation
annotations = .annotations*.annotationType()
( annotations)
( annotations)
The conversion from a meta-annotation to the collected annotations is performed during the semantic analysis compilation
phase.
In addition to replacing the alias with the collected annotations, a meta-annotation is capable of processing them, including
arguments.
Meta-annotation parameters
Meta-annotations can collect annotations which have parameters. To illustrate this, we will imagine two annotations, each of them
accepting one argument:
@Timeout(after=3600)
@Dangerous(type='explosive')
@Timeout(after=3600)
@Dangerous(type='explosive')
@AnnotationCollector
@interface {}
By default, when the annotations are replaced, they will get the annotation parameter values as they were de ned in the alias.
More interesting, the meta-annotation supports overriding speci c values:
@Explosive(after=0) 1
{}
1 the after value provided as a parameter to @Explosive overrides the one de ned in the @Timeout annotation
If two annotations de ne the same parameter name, the default processor will copy the annotation value to all annotations that
accept this parameter:
@Retention( .RUNTIME)
@interface {
value() 1
}
@Retention( .RUNTIME)
@interface {
value() 2
@Foo
@Bar
@AnnotationCollector
@interface {} 3
@Foo('a')
@Bar('b')
{} 4
@FooBar('a')
{} 7
In the second case, the meta-annotation value was copied in both @Foo and @Bar annotations.
It is a compile time error if the collected annotations de ne the same members with incompatible types. For
example if on the previous example @Foo de ned a value of type String but @Bar de ned a value of type int .
It is however possible to customize the behavior of meta-annotations and describe how collected annotations are expanded. We’ll
look at how to do that shortly but rst there is an advanced processing option to cover.
INFO: Custom processors (discussed next) may or may not support this parameter.
As an example, suppose you create a meta-annotation containing the @ToString annotation and then place your meta-
annotation on a class that already has an explicit @ToString annotation. Should this be an error? Should both annotations be
applied? Does one take priority over the other? There is no correct answer. In some scenarios it might be quite appropriate for
any of these answers to be correct. So, rather than trying to preempt one correct way to handle the duplicate annotation issue,
Groovy let’s you write your own custom meta-annotation processors (covered next) and let’s you write whatever checking logic
you like within AST transforms - which are a frequent target for aggregating. Having said that, by simply setting the mode , a
number of commonly expected scenarios are handled automatically for you within any extra coding. The behavior of the mode
parameter is determined by the AnnotationCollectorMode enum value chosen and is summarized in the following table.
Mode Description
PREFER_COLLECTOR Annotations from the collector will be added and any existing
annotations with the same name will be removed.
PREFER_COLLECTOR_MERGED Annotations from the collector will be added and any existing
annotations with the same name will be removed but any
new parameters found within existing annotations will be
merged into the added annotation.
http://docs.groovy-lang.org/latest/html/documentation/ 77/502
1/6/2019 create a meta-annotation processor, extending AnnotationCollectorTransform (http://docs.groovy-
Groovy Language Documentation
lang.org/2.5.5/html/gapi/index.html?org/codehaus/groovy/transform/AnnotationCollectorTransform.html)
To illustrate this, we are going to explore how the meta-annotation @CompileDynamic is implemented.
@CompileDynamic is a meta-annotation that expands itself to @CompileStatic(TypeCheckingMode.SKIP) . The problem is that
the default meta annotation processor doesn’t support enums and the annotation value TypeCheckingMode.SKIP is one.
@CompileStatic( .SKIP)
@AnnotationCollector
@interface {}
@AnnotationCollector(processor = "org.codehaus.groovy.transform.CompileDynamicProcessor")
@interface {
}
The rst thing you may notice is that our interface is no longer annotated with @CompileStatic . The reason for this is that we
rely on the processor parameter instead, that references a class which will generate the annotation.
CompileDynamicProcessor.groovy
@CompileStatic 1
{ 2
CS_NODE = .make( ) 3
TC_NODE = .make( ) 4
aliasAnnotationUsage, 6
aliasAnnotated, 7
source) { 8
node = (CS_NODE) 9
enumRef = (
(TC_NODE), "SKIP") 10
node.addMember("value", enumRef) 11
.singletonList(node) 12
}
}
1 our custom processor is written in Groovy, and for better compilation performance, we use static compilation
http://docs.groovy-lang.org/latest/html/documentation/ 78/502
1/6/2019 In the example, the visit method is the only method which hasLanguage
Groovy to be overridden. It is meant to return a list of annotation nodes
Documentation
that will be added to the node annotated with the meta-annotation. In this example, we return a single one corresponding to
@CompileStatic(TypeCheckingMode.SKIP) .
Inheritance
(TBD)
Generics
(TBD)
1.4.2. Traits
Traits are a structural construct of the language which allows:
composition of behaviors
behavior overriding
They can be seen as interfaces carrying both default implementations and state. A trait is de ned using the trait keyword:
trait { 1
1 declaration of a trait
2 declaration of a method inside a trait
Then it can be used like a normal interface using the implements keyword:
{} 1
b = () 2
Traits allow a wide range of capabilities, from simple composition to testing, which are described thoroughly in this section.
Methods
Public methods
Declaring a method in a trait can be done like any regular method in a class:
trait { 1
1 declaration of a trait
2 declaration of a method inside a trait
Abstract methods
In addition, traits may declare abstract methods too, which therefore need to be implemented in the class implementing the trait:
trait {
name() 1
http://docs.groovy-lang.org/latest/html/documentation/ 79/502
1/6/2019 1 Groovy Language Documentation
implementing class will have to declare the name method
2 can be mixed with a concrete method
{ 1
name() { 'Bob' } 2
p = ()
p.greeting() == 'Hello, Bob!' 3
Private methods
Traits may also de ne private methods. Those methods will not appear in the trait contract interface:
trait {
greetingMessage() { 1
println m
m
}
}
{} 3
g = ()
g.greet() == "Hello from a private method!" 4
{
g.greetingMessage() 5
} ( e) {
println "greetingMessage is private in trait"
}
Traits only support public and private methods. Neither protected nor package private scopes are
supported.
Final methods
If we have a class implementing a trait, conceptually implementations from the trait methods are "inherited" into the class. But, in
reality, there is no base class containing such implementations. Rather, they are woven directly into the class. A nal modi er on a
method just indicates what the modi er will be for the woven method. While it would likely be considered bad style to inherit and
override or multiply inherit methods with the same signature but a mix of nal and non- nal variants, Groovy doesn’t prohibit this
scenario. Normal method selection applies and the modi er used will be determined from the resulting method. You might
consider creating a base class which implements the desired trait(s) if you want trait implementation methods that can’t be
overridden.
http://docs.groovy-lang.org/latest/html/documentation/ 80/502
1/6/2019 Groovy Language Documentation
trait {
whoAmI() { }
}
{}
foo = ()
then calling:
foo.whoAmI()
foo.whoAmI(). (foo)
Interfaces
Traits may implement interfaces, in which case the interfaces are declared using the implements keyword:
{ 1
name()
}
trait { 2
name() { 'Bob' } 4
p = ()
p.greeting() == 'Hello, Bob!' 5
p 6
p 7
Properties
A trait may de ne properties, like in the following example:
trait {
name 1
}
{} 2
p = (name: 'Bob') 3
p.name == 'Bob' 4
p.getName() == 'Bob' 5
Fields
http://docs.groovy-lang.org/latest/html/documentation/ 81/502
1/6/2019 Private elds Groovy Language Documentation
Since traits allow the use of private methods, it can also be interesting to use private elds to store state. Traits will let you do that:
trait {
count = 0 1
}
{} 3
f = ()
f.count() == 1 4
f.count() == 2
Public elds
Public elds work the same way as private elds, but in order to avoid the diamond problem
(http://en.wikipedia.org/wiki/Multiple_inheritance#The_diamond_problem), eld names are remapped in the implementing class:
trait {
name 1
}
{} 2
p = () 3
p. = 'Bob' 4
The name of the eld depends on the fully quali ed name of the trait. All dots ( . ) in package are replaced with an underscore
( _ ), and the nal name includes a double underscore. So if the type of the eld is String , the name of the package is
my.package , the name of the trait is Foo and the name of the eld is bar , in the implementing class, the public eld will appear
as:
my_package_Foo__bar
While traits support public elds, it is not recommended to use them and considered as a bad practice.
Composition of behaviors
Traits can be used to implement multiple inheritance in a controlled way. For example, we can have the following traits:
trait { 1
}
trait {
speak() { "I'm speaking!" }
}
http://docs.groovy-lang.org/latest/html/documentation/ 82/502
1/6/2019 And a class implementing both traits: Groovy Language Documentation
, {} 1
d = () 2
Traits encourage the reuse of capabilities among objects, and the creation of new classes by the composition of existing behavior.
, {
quack() { "Quack!" } 1
speak() { quack() } 2
d = ()
d.fly() == "I'm flying!" 3
d.quack() == "Quack!" 4
d.speak() == "Quack!" 5
Extending traits
Simple inheritance
Traits may extend another trait, in which case you must use the extends keyword:
trait {
name 1
}
trait { 2
}
{}
p = (name: 'Alice') 4
Multiple inheritance
Alternatively, a trait may extend multiple traits. In that case, all super traits must be declared in the implements clause:
http://docs.groovy-lang.org/latest/html/documentation/ 83/502
1/6/2019 Groovy Language Documentation
trait { 1
id
}
trait { 2
name
}
trait , {} 3
Dynamic code
Traits can call any dynamic code, like a normal Groovy class. This means that you can, in the body of a method, call methods which
are supposed to exist in an implementing class, without having to explicitly declare them in an interface. This means that traits are
fully compatible with duck typing:
trait {
speak() { quack() } 1
}
{
methodMissing( name, args) {
"${name.capitalize()}!" 2
}
}
d = ()
d.speak() == 'Quack!' 3
trait { 1
props = [:]
methodMissing( name, args) {
name.toUpperCase()
}
propertyMissing( prop) {
props[prop]
}
setProperty( prop, value) {
props[prop] = value
}
}
{
existingProperty = 'ok' 2
existingMethod() { 'ok' } 3
}
d = ()
d.existingProperty == 'ok' 4
d.foo == 5
d.foo = 'bar' 6
d.foo == 'bar' 7
d.existingMethod() == 'ok' 8
d.someMethod() == 'SOMEMETHOD' 9
http://docs.groovy-lang.org/latest/html/documentation/ 84/502
1/6/2019 1 create a trait implementing several MOP methods Groovy Language Documentation
2 the Dynamic class de nes a property
3 the Dynamic class de nes a method
4 calling an existing property will call the method from Dynamic
5 calling an non-existing property will call the method from the trait
6 will call setProperty de ned on the trait
7 will call getProperty de ned on the trait
8 calling an existing method on Dynamic
9 but calling a non existing method thanks to the trait methodMissing
trait A {
() { 'A' } 1
}
trait B {
() { 'B' } 2
}
C A,B {} 3
In this case, the default behavior is that the method from the last declared trait in the implements clause wins. Here, B is
declared after A so the method from B will be picked up:
c = C()
c. () == 'B'
C A,B {
() { A. . () } 1
}
c = C()
c. () == 'A' 2
http://docs.groovy-lang.org/latest/html/documentation/ 85/502
1/6/2019 Groovy Language Documentation
trait {
extra() { "I'm an extra method" } 1
}
{ 2
doSomething() { 'Something' } 3
Then if we do:
s = ()
s.extra()
the call to extra would fail because Something is not implementing Extra . It is possible to do it at runtime with the following
syntax:
s = () 1
s.extra() 2
s.doSomething() 3
When coercing an object to a trait, the result of the operation is not the same instance. It is guaranteed that the
coerced object will implement both the trait and the interfaces that the original object implements, but the result
will not be an instance of the original class.
trait A { methodFromA() {} }
trait B { methodFromB() {} }
C {}
c = C()
c.methodFromA() 1
c.methodFromB() 2
d = c.withTraits A, B 3
d.methodFromA() 4
d.methodFromB() 5
When coercing an object to multiple traits, the result of the operation is not the same instance. It is guaranteed
that the coerced object will implement both the traits and the interfaces that the original object implements, but
the result will not be an instance of the original class.
Chaining behavior
http://docs.groovy-lang.org/latest/html/documentation/ 86/502
1/6/2019 Groovy supports the concept of stackable traits. The idea Groovy
is to delegate from
Language one trait to the other if the current trait is not
Documentation
capable of handling a message. To illustrate this, let’s imagine a message handler interface like this:
{
on( message, payload)
}
Then you can compose a message handler by applying small behaviors. For example, let’s de ne a default handler in the form of a
trait:
trait {
on( message, payload) {
println "Received $message with payload $payload"
}
}
Then any class can inherit the behavior of the default handler by implementing the trait:
{}
Now what if you want to log all messages, in addition to the default handler? One option is to write this:
{
on( message, payload) { 1
. .on(message, payload) 3
}
}
2. we have an explicit reference to DefaultHandler in the on method, meaning that if we happen to change the trait that our
class implements, code will be broken
trait { 1
.on(message, payload) 3
}
}
, {}
loggingHandler = ()
loggingHandler.on('test logging', [:])
As the priority rules imply that LoggerHandler wins because it is declared last, then a call to on will use the implementation
from LoggingHandler . But the latter has a call to super , which means the next trait in the chain. Here, the next trait is
DefaultHandler so both will be called:
The interest of this approach becomes more evident if we add a third handler, which is responsible for handling messages that
start with say :
trait {
on( message, payload) {
(message.startsWith("say")) { 1
}
}
}
, , {}
h = ()
h.on('foo', [:])
h.on('sayHello', [:])
Which means:
the logging handler calls super which will delegate to the next handler, which is the SayHandler
if the message starts with say , then the handler consumes the message
if not, the say handler delegates to the next handler in the chain
This approach is very powerful because it allows you to write handlers that do not know each other and yet let you combine them
in the order you want. For example, if we execute the code, it will print:
but if we move the logging handler to be the second one in the chain, the output is di erent:
, , {}
h = ()
h.on('foo', [:])
h.on('sayHello', [:])
prints:
The reason is that now, since the SayHandler consumes the message without calling super , the logging handler is not called
anymore.
http://docs.groovy-lang.org/latest/html/documentation/ 88/502
1/6/2019 Semantics of super inside a trait Groovy Language Documentation
If a class implements multiple traits and a call to an unquali ed super is found, then:
1. if the class implements another trait, the call delegates to the next trait in the chain
2. if there isn’t any trait left in the chain, super refers to the super class of the implementing class (this)
trait { 1
append( str) { 2
subst = str.replace('o','') 3
.append(subst) 4
}
toString() { .toString() } 5
}
sb = ().withTraits 6
sb.append('Groovy')
sb.toString() == 'Grvy' 7
In this example, when super.append is encountered, there is no other trait implemented by the target object, so the method
which is called is the original append method, that is to say the one from StringBuilder . The same trick is used for toString ,
so that the string representation of the proxy object which is generated delegates to the toString of the StringBuilder
instance.
Advanced features
trait {
greet() { "Hello $name" } 1
getName() 2
1 the greet method is not abstract and calls the abstract method getName
2 getName is an abstract method
Since getName is the single abstract method in the Greeter trait, you can write:
greeter = { 'Alice' } 1
1 the closure "becomes" the implementation of the getName single abstract method
or even:
greet { 'Alice' } 2
This feature can be used to compose behaviors in an very precise way, in case you want to override the behavior of an already
implemented method.
groovy.transform.
org.codehaus.groovy.control.
org.codehaus.groovy.control.customizers.
org.codehaus.groovy.control.customizers.
{
config
shell
setup() {
config = ()
shell = (config)
}
testSomething() {
shell.evaluate('1+1') == 2
}
otherTest() { /* ... */ }
}
In this example, we create a simple test case which uses two properties (con g and shell) and uses those in multiple test methods.
Now imagine that you want to test the same, but with another distinct compiler con guration. One option is to create a subclass
of SomeTest :
{
setup() {
config = ()
config.addCompilationCustomizers( ... )
shell = (config)
}
}
It works, but what if you have actually multiple test classes, and that you want to test the new con guration for all those test
classes? Then you would have to create a distinct subclass for each test class:
{
setup() {
config = ()
config.addCompilationCustomizers( ... )
shell = (config)
}
}
Then what you see is that the setup method of both tests is the same. The idea, then, is to create a trait:
trait {
setup() {
config = ()
config.addCompilationCustomizers( ( ) )
shell = (config)
}
}
http://docs.groovy-lang.org/latest/html/documentation/ 90/502
1/6/2019 Then use it in the subclasses: Groovy Language Documentation
{}
{}
...
It would allow us to dramatically reduce the boilerplate code, and reduces the risk of forgetting to change the setup code in case
we decide to change it. Even if setup is already implemented in the super class, since the test class declares the trait in its
interface list, the behavior will be borrowed from the trait implementation!
This feature is in particular useful when you don’t have access to the super class source code. It can be used to mock methods or
force a particular implementation of a method in a subclass. It lets you refactor your code to keep the overridden logic in a single
trait and inherit a new behavior just by implementing it. The alternative, of course, is to override the method in every place you
would have used the new code.
It’s worth noting that if you use runtime traits, the methods from the trait are always preferred to those of the
proxied object:
{
name 1
}
trait {
getName() { 'Bob' } 2
p = (name: 'Alice')
p.name == 'Alice' 3
p2 = p 4
p2.name == 'Bob' 5
1 the Person class de nes a name property which results in a getName method
2 Bob is a trait which de nes getName as returning Bob
3 the default object will return Alice
4 p2 coerces p into Bob at runtime
5 getName returns Bob because getName is taken from the trait
Again, don’t forget that dynamic trait coercion returns a distinct object which only implements the original
interfaces, as well as the traits.
internally, the trait is represented as an interface (without default or static methods) and several helper classes
Methods added through a mixin are, on the contrary, only visible at runtime:
http://docs.groovy-lang.org/latest/html/documentation/ 91/502
1/6/2019 Groovy Language Documentation
A { methodFromA() { 'A' } } 1
B { methodFromB() { 'B' } } 2
A.metaClass.mixin B 3
o = A()
o.methodFromA() == 'A' 4
o.methodFromB() == 'B' 5
o A 6
!(o B) 7
The last point is actually a very important and illustrates a place where mixins have an advantage over traits: the instances are not
modi ed, so if you mixin some class into another, there isn’t a third class generated, and methods which respond to A will
continue responding to A even if mixed in.
The following instructions are subject to caution. Static member support is work in progress and still
experimental. The information below is valid for 2.5.5 only.
Traits with static methods cannot be compiled statically or type checked. All static methods, properties and eld are accessed
dynamically (it’s a limitation from the JVM).
Static methods do not appear within the generated interfaces for each trait.
The trait is interpreted as a template for the implementing class, which means that each implementing class will get its own
static methods, properties and elds. So a static member declared on a trait doesn’t belong to the Trait , but to it’s
implementing class.
You should typically not mix static and instance methods of the same signature. The normal rules for applying traits apply
(including multiple inheritance con ict resolution). If the method chosen is static but some implemented trait has an instance
variant, a compilation error will occur. If the method chosen is the instance variant, the static variant will be ignored (the
behavior is similar to static methods in Java interfaces for this case).
trait {
CALLED = 1
init() { 2
CALLED = 3
}
}
{}
.init() 4
. 5
http://docs.groovy-lang.org/latest/html/documentation/ 92/502
1/6/2019 As usual, it is not recommended to use public elds. Anyway, should
Groovy you want
Language this, you must understand that the following code
Documentation
would fail:
.CALLED =
because there is no static eld CALLED de ned on the trait itself. Likewise, if you have two distinct implementing classes, each one
gets a distinct static eld:
{} 1
{} 2
.init() 3
. 4
! . 5
trait {
x = 1
y = 2
sum() { x+y }
}
The trait de nes two properties, x and y , as well as a sum method. Now let’s create a class which implements the trait:
{
f() { sum() }
}
= ()
.f() == 3
The result of calling f is 3 , because f delegates to sum in the trait, which has state. But what if we write this instead?
{
x = 3 1
y = 4 2
f() { sum() } 3
}
elem = ()
1 Override property x
2 Override property y
3 Call sum from trait
elem.f() == 3
The reason is that the sum method accesses the elds of the trait. So it is using the x and y values de ned in the trait. If you
want to use the values from the implementing class, then you need to dereference elds by using getters and setters, like in this
last example:
http://docs.groovy-lang.org/latest/html/documentation/ 93/502
1/6/2019 Groovy Language Documentation
trait {
x = 1
y = 2
sum() { getX()+getY() }
}
{
x = 3
y = 4
f() { sum() }
}
elem = ()
elem.f() == 7
Self types
{
sendMessage( , to, message) { 1
{ id } 2
trait {
sendMessage( to, message) {
.sendMessage(id, to.id, message) 3
}
}
{} 4
bob = (id:'Bob')
alice = (id:'Alice')
bob.sendMessage(alice,'secret') 5
1 A Service class, beyond your control (in a library, …) de nes a sendMessage method
2 A Device class, beyond your control (in a library, …)
3 De nes a communicating trait for devices that can call the service
4 De nes MyDevice as a communicating device
5 The method from the trait is called, and id is resolved
It is clear, here, that the Communicating trait can only apply to Device . However, there’s no explicit contract to indicate that,
because traits cannot extend classes. However, the code compiles and runs perfectly ne, because id in the trait method will be
resolved dynamically. The problem is that there is nothing that prevents the trait from being applied to any class which is not a
Device . Any class which has an id would work, while any class that does not have an id property would cause a runtime error.
The problem is even more complex if you want to enable type checking or apply @CompileStatic on the trait: because the trait
knows nothing about itself being a Device , the type checker will complain saying that it does not nd the id property.
One possibility is to explicitly add a getId method in the trait, but it would not solve all issues. What if a method requires this
as a parameter, and actually requires it to be a Device ?
{
check( d) { (d.id== ) () }
}
http://docs.groovy-lang.org/latest/html/documentation/ 94/502
1/6/2019 If you want to be able to call this in the trait, then you will explicitly
Groovy need to
Language cast this into a Device . This can quickly become
Documentation
unreadable with explicit casts to this everywhere.
let you declare the types that a class that implements this trait must inherit or implement
throw a compile time error if those type constraints are not satis ed
So in our previous example, we can x the trait using the @groovy.transform.SelfType annotation:
@SelfType( )
@CompileStatic
trait {
sendMessage( to, message) {
.check( )
.sendMessage(id, to.id, message)
}
}
Now if you try to implement this trait on a class that is not a device, a compile-time error will occur:
class 'MyDevice' implements trait 'Communicating' but does not extend self type class 'Device'
In conclusion, self types are a powerful way of declaring constraints on traits without having to declare the contract directly in the
trait or having to use casts everywhere, maintaining separation of concerns as tight as it should be.
Limitations
Traits are not o cially compatible with AST transformations. Some of them, like @CompileStatic will be applied
on the trait itself (not on implementing classes), while others will apply on both the implementing class and the
trait. There is absolutely no guarantee that an AST transformation will run on a trait as it does on a regular class,
so use it at your own risk!
trait {
x
inc() {
x++ 1
}
dec() {
--x 2
}
}
{}
c = ()
c.inc()
This chapter covers Groovy Closures. A closure in Groovy is an open, anonymous, block of code that can take arguments, return a
value and be assigned to a variable. A closure may reference variables declared in its surrounding scope. In opposition to the
formal de nition of a closure, Closure in the Groovy language can also contain free variables which are de ned outside of its
surrounding scope. While breaking the formal concept of a closure, it o ers a variety of advantages which are described in this
chapter.
1.5.1. Syntax
De ning a closure
A closure de nition follows this syntax:
Where [closureParameters->] is an optional comma-delimited list of parameters, and statements are 0 or more Groovy
statements. The parameters look similar to a method parameter list, and these parameters may be typed or untyped.
When a parameter list is speci ed, the -> character is required and serves to separate the arguments from the closure body. The
statements portion consists of 0, 1, or many Groovy statements.
{ item++ } 1
{ -> item++ } 2
{ println it } 3
{ it -> println it } 4
{ x, y -> 6
{ reader -> 7
line = reader.readLine()
line.trim()
}
Closures as an object
A closure is an instance of the groovy.lang.Closure class, making it assignable to a variable or a eld as any other variable,
despite being a block of code:
listener
callback = { println 'Done!' } 2
http://docs.groovy-lang.org/latest/html/documentation/ 96/502
1/6/2019 1 Groovy Language
You can assign a closure to a variable, and it is an instance Documentation
of groovy.lang.Closure
2 If not using def , you can assign a closure to a variable of type groovy.lang.Closure
3 Optionally, you can specify the return type of the closure by using the generic type of groovy.lang.Closure
Calling a closure
A closure, as an anonymous block of code, can be called like any other method. If you de ne a closure which takes no argument
like this:
code = { 123 }
Then the code inside the closure will only be executed when you call the closure, which can be done by using the variable as if it
was a regular method:
code() == 123
code.call() == 123
isOdd(3) == 2
isOdd.call(2) == 3
isEven = { it%2 == 0 } 4
isEven(3) == 5
isEven.call(2) == 6
Unlike a method, a closure always returns a value when called. The next section discusses how to declare closure arguments,
when to use them and what is the implicit "it" parameter.
1.5.2. Parameters
Normal parameters
Parameters of closures follow the same principle as parameters of regular methods:
an optional type
a name
http://docs.groovy-lang.org/latest/html/documentation/ 97/502
1/6/2019 Groovy Language Documentation
closureWithOneArg = { str -> str.toUpperCase() }
closureWithOneArg('groovy') == 'GROOVY'
Implicit parameter
When a closure does not explicitly de ne a parameter list (using -> ), a closure always de nes an implicit parameter, named it .
This means that this code:
If you want to declare a closure which accepts no argument and must be restricted to calls without arguments, then you must
declare it with an explicit empty argument list:
magicNumber = { -> 42 }
// this call will fail because the closure doesn't accept any argument
magicNumber(11)
Varargs
It is possible for a closure to declare variable arguments like any other method. Vargs methods are methods that can accept a
variable number of arguments if the last parameter is of variable length (or an array) like in the next examples:
concat1('abc','def') == 'abcdef' 2
args.join('')*n
}
multiConcat(2, 'abc','def') == 'abcdefabcdef'
owner corresponds to the enclosing object where the closure is de ned, which may be either a class or a closure
delegate corresponds to a third party object where methods calls or properties are resolved whenever the receiver of the
message is not de ned
{
run() {
whatIsThisObject = { getThisObject() } 1
whatIsThisObject() == 2
whatIsThis = { } 3
whatIsThis() == 4
}
}
{
{
cl = { } 5
}
run() {
inner = ()
inner.cl() == inner 6
}
}
{
run() {
nestedClosures = {
cl = { } 7
cl()
}
nestedClosures() == 8
}
}
It is of course possible to call methods from the enclosing class this way:
http://docs.groovy-lang.org/latest/html/documentation/ 99/502
1/6/2019 Groovy Language Documentation
{
name
age
toString() { "$name is $age years old" }
() {
cl = {
msg = .toString() 1
println msg
msg
}
cl()
}
}
p = (name:'Janice', age:74)
p. () == 'Janice is 74 years old'
the closure calls toString on this , which will actually call the toString method on the enclosing object, that is to say
1
the Person instance
Owner of a closure
The owner of a closure is very similar to the de nition of this in a closure with a subtle di erence: it will return the direct enclosing
object, be it a closure or a class:
{
run() {
whatIsOwnerMethod = { getOwner() } 1
whatIsOwnerMethod() == 2
whatIsOwner = { owner } 3
whatIsOwner() == 4
}
}
{
{
cl = { owner } 5
}
run() {
inner = ()
inner.cl() == inner 6
}
}
{
run() {
nestedClosures = {
cl = { owner } 7
cl()
}
nestedClosures() == nestedClosures 8
}
}
Delegate of a closure
http://docs.groovy-lang.org/latest/html/documentation/ 100/502
1/6/2019 The delegate of a closure can be accessed by using the delegate propertyDocumentation
Groovy Language or calling the getDelegate method. It is a powerful
concept for building domain speci c languages in Groovy. While closure-this and closure-owner refer to the lexical scope of a
closure, the delegate is a user de ned object that a closure will use. By default, the delegate is set to owner :
{
run() {
cl = { getDelegate() } 1
cl2 = { } 2
cl() == cl2() 3
cl() == 4
enclosed = {
{ -> }.call() 5
}
enclosed() == enclosed 6
}
}
1 you can get the delegate of a closure calling the getDelegate method
2 or using the delegate property
3 both return the same object
4 which is the enclosing class or closure
5 in particular in case of nested closures
6 delegate will correspond to the owner
The delegate of a closure can be changed to any object. Let’s illustrate this by creating two classes which are not subclasses of
each other but both de ne a property called name :
{
name
}
{
name
}
p = (name: 'Norman')
t = (name: 'Teapot')
Then let’s de ne a closure which fetches the name property on the delegate:
upperCasedName = { .name.toUpperCase() }
Then by changing the delegate of the closure, you can see that the target object will change:
upperCasedName. = p
upperCasedName() == 'NORMAN'
upperCasedName. = t
upperCasedName() == 'TEAPOT'
At this point, the behavior is not di erent from having a target variable de ned in the lexical scope of the closure:
target = p
upperCasedNameUsingVar = { target.name.toUpperCase() }
upperCasedNameUsingVar() == 'NORMAN'
in the last example, target is a local variable referenced from within the closure
the delegate can be used transparently, that is to say without pre xing method calls with delegate. as explained in the next
paragraph.
http://docs.groovy-lang.org/latest/html/documentation/ 101/502
1/6/2019 Delegation strategy Groovy Language Documentation
Whenever, in a closure, a property is accessed without explicitly setting a receiver object, then a delegation strategy is involved:
{
name
}
p = (name:'Igor')
cl = { name.toUpperCase() } 1
cl. = p 2
cl() == 'IGOR' 3
The reason this code works is that the name property will be resolved transparently on the delegate object! This is a very
powerful way to resolve properties or method calls inside closures. There’s no need to set an explicit delegate. receiver: the call
will be made because the default delegation strategy of the closure makes it so. A closure actually de nes multiple resolution
strategies that you can choose:
Closure.OWNER_FIRST is the default strategy. If a property/method exists on the owner, then it will be called on the owner. If
not, then the delegate is used.
Closure.DELEGATE_FIRST reverses the logic: the delegate is used rst, then the owner
Closure.OWNER_ONLY will only resolve the property/method lookup on the owner: the delegate will be ignored.
Closure.DELEGATE_ONLY will only resolve the property/method lookup on the delegate: the owner will be ignored.
Closure.TO_SELF can be used by developers who need advanced meta-programming techniques and wish to implement a
custom resolution strategy: the resolution will not be made on the owner or the delegate but only on the closure class itself. It
makes only sense to use this if you implement your own subclass of Closure .
Let’s illustrate the default "owner rst" strategy with this code:
{
name
pretty = { "My name is $name" } 1
toString() {
pretty()
}
}
{
name 2
p = (name: 'Sarah')
t = (name: 'Teapot')
p.pretty. = t 4
p.pretty.resolveStrategy = .DELEGATE_FIRST
p.toString() == 'My name is Teapot'
http://docs.groovy-lang.org/latest/html/documentation/ 102/502
1/6/2019 By changing the resolveStrategy , we are modifying theGroovy
way Groovy will resolve
Language the "implicit this" references: in this case, name
Documentation
will rst be looked in the delegate, then if not found, on the owner. Since name is de ned in the delegate, an instance of Thing ,
then this value is used.
The di erence between "delegate rst" and "delegate only" or "owner rst" and "owner only" can be illustrated if one of the
delegate (resp. owner) does not have such a method or property:
{
name
age
fetchAge = { age }
}
{
name
}
p = (name:'Jessica', age:42)
t = (name:'Printer')
cl = p.fetchAge
cl. = p
cl() == 42
cl. = t
cl() == 42
cl.resolveStrategy = .DELEGATE_ONLY
cl. = p
cl() == 42
cl. = t
{
cl()
} ( ex) {
// "age" is not defined on the delegate
}
In this example, we de ne two classes which both have a name property but only the Person class declares an age . The
Person class also declares a closure which references age . We can change the default resolution strategy from "owner rst" to
"delegate only". Since the owner of the closure is the Person class, then we can check that if the delegate is an instance of
Person , calling the closure is successful, but if we call it with a delegate being an instance of Thing , it fails with a
groovy.lang.MissingPropertyException . Despite the closure being de ned inside the Person class, the owner is not used.
A comprehensive explanation about how to use this feature to develop DSLs can be found in a dedicated section
of the manual (core-domain-speci c-languages.html).
x = 1
gs = "x = ${x}"
gs == 'x = 1'
The code behaves as you would expect, but what happens if you add:
x = 2
gs == 'x = 2'
You will see that the assert fails! There are two reasons for this:
the syntax ${x} in a GString does not represent a closure but an expression to $x , evaluated when the GString is created.
http://docs.groovy-lang.org/latest/html/documentation/ 103/502
1/6/2019 In our example, the GString is created with an expression referencing
Groovy x . Documentation
Language When the GString is created, the value of x is 1, so
the GString is created with a value of 1. When the assert is triggered, the GString is evaluated and 1 is converted to a String
using toString . When we change x to 2, we did change the value of x , but it is a di erent object, and the GString still
references the old one.
A GString will only change its toString representation if the values it references are mutating. If the references
change, nothing will happen.
If you need a real closure in a GString and for example enforce lazy evaluation of variables, you need to use the alternate syntax
${→ x} like in the xed example:
x = 1
gs = "x = ${-> x}"
gs == 'x = 1'
x = 2
gs == 'x = 2'
And let’s illustrate how it di ers from mutation with this code:
{
name
toString() { name } 1
}
sam = (name:'Sam') 2
lucy = (name:'Lucy') 3
p = sam 4
gs = "Name: ${p}" 5
gs == 'Name: Sam' 6
p = lucy 7
gs == 'Name: Sam' 8
sam.name = 'Lucy' 9
gs == 'Name: Lucy' 10
1 the Person class has a toString method returning the name property
2 we create a rst Person named Sam
3 we create another Person named Lucy
4 the p variable is set to Sam
5 and a closure is created, referencing the value of p , that is to say Sam
6 so when we evaluate the string, it returns Sam
7 if we change p to Lucy
8 the string still evaluates to Sam because it was the value of p when the GString was created
9 so if we mutate Sam to change his name to Lucy
10 this time the GString is correctly mutated
So if you don’t want to rely on mutating objects or wrapping objects, you must use closures in GString by explicitly declaring an
empty argument list:
http://docs.groovy-lang.org/latest/html/documentation/ 104/502
1/6/2019 Groovy Language Documentation
{
name
toString() { name }
}
sam = (name:'Sam')
lucy = (name:'Lucy')
p = sam
// Create a GString with lazy evaluation of "p"
gs = "Name: ${-> p}"
gs == 'Name: Sam'
p = lucy
gs == 'Name: Lucy'
Currying
In Groovy, currying refers to the concept of partial application. It does not correspond to the real concept of currying in functional
programming because of the di erent scoping rules that Groovy applies on closures. Currying in Groovy will let you set the value
of one parameter of a closure, and it will return a new closure accepting one less argument.
Left currying
Left currying is the fact of setting the left-most parameter of a closure, like in this example:
twice = nCopies.curry(2) 2
twice('bla') == 'blabla' 3
Right currying
Similarily to left currying, it is possible to set the right-most parameter of a closure:
blah = nCopies.rcurry('bla') 2
blah(2) == 'blabla' 3
http://docs.groovy-lang.org/latest/html/documentation/ 105/502
1/6/2019 Groovy Language Documentation
volume = { l, w, h -> l*w*h } 1
Memoization
Memoization allows the result of the call of a closure to be cached. It is interesting if the computation done by a function (closure)
is slow, but you know that this function is going to be called often with the same arguments. A typical example is the Fibonacci
suite. A naive implementation may look like this:
fib
fib = { n -> n<2?n:fib(n-1)+fib(n-2) }
fib(15) == 610 // slow!
It is a naive implementation because ' b' is often called recursively with the same arguments, leading to an exponential algorithm:
Since calls are recursive, you can already see that we will compute the same values again and again, although they could be
cached. This naive implementation can be " xed" by caching the result of calls using memoize :
The cache works using the actual values of the arguments. This means that you should be very careful if you use
memoization with something else than primitive or boxed primitive types.
memoizeBetween will generate a new closure which caches at least n values and at most n values
Composition
Closure composition corresponds to the concept of function composition, that is to say creating a new function by composing two
or more functions (chaining calls), as illustrated in this example:
http://docs.groovy-lang.org/latest/html/documentation/ 106/502
1/6/2019 Groovy Language Documentation
plus2 = { it + 2 }
times3 = { it * 3 }
// reverse composition
times3plus2(3) == (times3 >> plus2)(3)
Trampoline
Recursive algorithms are often restricted by a physical limit: the maximum stack height. For example, if you call a method that
recursively calls itself too deep, you will eventually receive a StackOverflowException .
An approach that helps in those situations is by using Closure and its trampoline capability.
Closures are wrapped in a TrampolineClosure . Upon calling, a trampolined Closure will call the original Closure waiting for
its result. If the outcome of the call is another instance of a TrampolineClosure , created perhaps as a result to a call to the
trampoline() method, the Closure will again be invoked. This repetitive invocation of returned trampolined Closures instances
will continue until a value other than a trampolined Closure is returned. That value will become the nal result of the
trampoline. That way, calls are made serially, rather than lling the stack.
factorial
factorial = { n, accu = 1G ->
(n < 2) accu
factorial.trampoline(n - 1, n * accu)
}
factorial = factorial.trampoline()
factorial(1) == 1
factorial(3) == 1 * 2 * 3
factorial(1000) // == 402387260.. plus another 2560 digits
Method pointers
It is often practical to be able to use a regular method as a closure. For example, you might want to use the currying abilities of a
closure, but those are not available to normal methods. In Groovy, you can obtain a closure from any method with the method
pointer operator (core-operators.html#method-pointer-operator).
1.6. Semantics
This chapter covers the semantics of the Groovy programming language.
1.6.1. Statements
Variable de nition
Variables can be de ned using either their type (like String ) or by using the keyword def :
x
o
def is a replacement for a type name. In variable de nitions it is used to indicate that you don’t care about the type. In variable
de nitions it is mandatory to either provide a type name explicitly or to use "def" in replacement. This is needed to make variable
de nitions detectable for the Groovy parser.
You can think of def as an alias of Object and you will understand it in an instant.
http://docs.groovy-lang.org/latest/html/documentation/ 107/502
1/6/2019 Groovy Language Documentation
Variable de nition types can be re ned by using generics, like in List<String> names . To learn more about the
generics support, please read the generics section.
Variable assignment
You can assign values to variables for later use. Try the following:
x = 1
println x
x = java.util. ()
println x
x = -3.1499392
println x
x =
println x
x = "Hi"
println x
Multiple assignment
Groovy supports multiple assignment, i.e. where multiple variables can be assigned at once, e.g.:
( i, j) = [10, 'foo']
i == 10 && j == 'foo'
nums = [1, 3, 5]
a, b, c
(a, b, c) = nums
a == 1 && b == 3 && c == 5
The syntax works for arrays as well as lists, as well as methods that return either of these:
(a, b, c) = [1, 2]
a == 1 && b == 2 && c ==
If the right hand side has too many variables, the extra ones are ignored:
(a, b) = [1, 2, 3]
a == 1 && b == 2
http://docs.groovy-lang.org/latest/html/documentation/ 108/502
1/6/2019 With this technique, we can combine multiple assignments and the
Groovy subscript
Language operator methods to implement object
Documentation
destructuring.
Consider the following immutable Coordinates class, containing a pair of longitude and latitude doubles, and notice our
implementation of the getAt() method:
@Immutable
{
latitude
longitude
getAt( idx) {
(idx == 0) latitude
(idx == 1) longitude
("Wrong coordinate index, use 0 or 1")
}
}
Now let’s instantiate this class and destructure its longitude and latitude:
la == 43.23 3
lo == 3.67
Control structures
Conditional structures
if / else
Groovy supports the usual if - else syntax from Java
x =
y =
( !x ) {
x =
}
x ==
( x ) {
x =
} {
y =
}
x == y
Groovy also supports the normal Java "nested" if then else if syntax:
( ... ) {
...
} (...) {
...
} {
...
}
http://docs.groovy-lang.org/latest/html/documentation/ 109/502
1/6/2019 switch / case Groovy Language Documentation
The switch statement in Groovy is backwards compatible with Java code; so you can fall through cases sharing the same code for
multiple matches.
One di erence though is that the Groovy switch statement can handle any kind of switch value and di erent kinds of matching
can be performed.
x = 1.23
result = ""
( x ) {
"foo":
result = "found foo"
// lets fall through
"bar":
result += "bar"
[4, 5, 6, 'inList']:
result = "list"
12..30:
result = "range"
:
result = "integer"
:
result = "number"
{ it < 0 }: // or { x < 0 }
result = "negative"
:
result = "default"
}
result == "number"
Class case values match if the switch value is an instance of the class
Regular expression case values match if the toString() representation of the switch value matches the regex
Collection case values match if the switch value is contained in the collection. This also includes ranges (since they are Lists)
Closure case values match if the calling the closure returns a result which is true according to the Groovy truth
If none of the above are used then the case value matches if the case value equals the switch value
When using a closure case value, the default it parameter is actually the switch value (in our example, variable
x ).
Looping structures
Classic for loop
Groovy supports the standard Java / C for loop:
http://docs.groovy-lang.org/latest/html/documentation/ 110/502
1/6/2019 Groovy Language Documentation
message = ''
( i = 0; i < 5; i++) {
message += 'Hi '
}
message == 'Hi Hi Hi Hi Hi '
for in loop
The for loop in Groovy is much simpler and works with any kind of array, collection, Map, etc.
Groovy also supports the Java colon variation with colons: for (char c : text) {} , where the type of the
variable is mandatory.
while loop
Groovy supports the usual while {…} loops like Java:
http://docs.groovy-lang.org/latest/html/documentation/ 111/502
1/6/2019 Groovy Language Documentation
x = 0
y = 5
( y-- > 0 ) {
x++
}
x == 5
Exception handling
Exception handling is the same as Java.
{
'moo'.toLong() // this will generate an exception
// asserting that this point should never be reached
} ( e ) {
e
}
We can put code within a ' nally' clause following a matching 'try' clause, so that regardless of whether the code in the 'try' clause
throws an exception, the code in the nally clause will always execute:
z
{
i = 7, j = 0
{
k = i / j
//never reached due to Exception in previous line
} {
z = 'reached here' //always executed even if Exception thrown
}
} ( e ) {
e
z == 'reached here'
}
Multi-catch
With the multi catch block (since Groovy 2.0), we’re able to de ne several exceptions to be catch and treated by the same catch
block:
{
/* ... */
} ( | e ) {
/* one block to handle 2 exceptions */
}
Power assertion
Unlike Java with which Groovy shares the assert keyword, the latter in Groovy behaves very di erently. First of all, an assertion
in Groovy is always executed, independently of the -ea ag of the JVM. It makes this a rst class choice for unit tests. The notion
of "power asserts" is directly related to how the Groovy assert behaves.
http://docs.groovy-lang.org/latest/html/documentation/ 112/502
1/6/2019 The result of the assertion is very di erent from what youGroovy
would Language
get in Java.Documentation
If the assertion is true, then nothing happens. If the
assertion is false, then it provides a visual representation of the value of each sub-expressions of the expression being asserted.
For example:
1+1 == 3
Will yield:
assert 1+1 == 3
| |
2 false
Power asserts become very interesting when the expressions are more complex, like in the next example:
x = 2
y = 7
z = 5
calc = { a,b -> a*b+1 }
calc(x,y) == [x,z].sum()
calc(x,y) == [x,z].sum()
| | | | | | |
15 2 7 | 2 5 7
In case you don’t want a pretty printed error message like above, you can fallback to a custom error message by changing the
optional message part of the assertion, like in this example:
x = 2
y = 7
z = 5
calc = { a,b -> a*b+1 }
calc(x,y) == z*z : 'Incorrect computation result'
Labeled statements
Any statement can be associated with a label. Labels do not impact the semantics of the code and can be used to make the code
easier to read like in the following example:
given:
x = 1
y = 2
:
z = x+y
:
z == 3
Despite not changing the semantics of the the labelled statement, it is possible to use labels in the break instruction as a target
for jump, as in the next example. However, even if this is allowed, this coding style is in general considered a bad practice:
http://docs.groovy-lang.org/latest/html/documentation/ 113/502
1/6/2019 Groovy Language Documentation
( i=0;i<10;i++) {
( j=0;j<i;j++) {
println "j=$j"
(j == 5) {
}
}
: println "i=$i"
}
It is important to understand that by default labels have no impact on the semantics of the code, however they belong to the
abstract syntax tree (AST) so it is possible for an AST transformation to use that information to perform transformations over the
code, hence leading to di erent semantics. This is in particular what the Spock Framework
(http://spockframework.github.io/spock/docs/current/index.html) does to make testing easier.
1.6.2. Expressions
(TBD)
GPath expressions
GPath is a path expression language integrated into Groovy which allows parts of nested structured data to be identi ed. In this
sense, it has similar aims and scope as XPath does for XML. GPath is often used in the context of processing XML, but it really
applies to any object graph. Where XPath uses a lesystem-like path notation, a tree hierarchy with parts separated by a slash / ,
GPath use a dot-object notation to perform object navigation.
a.b.c → for POJOs, yields the c properties for all the b properties of a (sort of like a.getB().getC() in JavaBeans)
In both cases, the GPath expression can be viewed as a query on an object graph. For POJOs, the object graph is most often built
by the program being written through object instantiation and composition; for XML processing, the object graph is the result of
parsing the XML text, most often with classes like XmlParser or XmlSlurper. See Processing XML (..\..\../subprojects/groovy-
xml/src/spec/doc/xml-userguide.html#Processing XML) for more in-depth details on consuming XML in Groovy.
When querying the object graph generated from XmlParser or XmlSlurper, a GPath expression can refer to
attributes de ned on elements with the @ notation:
Object navigation
Let’s see an example of a GPath expression on a simple object graph, the one obtained using java re ection. Suppose you are in a
non-static method of a class having another method named aMethodFoo
the following GPath expression will get the name of that method:
['aMethodFoo'] == . .methods.name.grep(~/.*Foo/)
More precisely, the above GPath expression produces a list of String, each being the name of an existing method on this where
that name ends with Foo .
Expression Deconstruction
We can decompose the expression this.class.methods.name.grep(~/.*Bar/) to get an idea of how a GPath is evaluated:
this.class
this.class.methods
this.class.methods.name
apply a property accessor on each element of an array and produce a list of the results.
this.class.methods.name.grep(…)
call method grep on each element of the list yielded by this.class.methods.name and produce a list of the results.
One powerful feature of GPath expression is that property access on a collection is converted to a property access on each
element of the collection with the results collected into a collection. Therefore, the expression this.class.methods.name could
be expressed as follows in Java:
Array access notation can also be used in a GPath expression where a collection is present :
'aSecondMethodBar' == . .methods.name.grep(~/.*Bar/).sort()[1]
http://docs.groovy-lang.org/latest/html/documentation/ 115/502
1/6/2019 Groovy Language Documentation
xmlText = """
| <root>
| <level>
| <sublevel id='1'>
| <keyVal>
| <key>mykey</key>
| <value>value 123</value>
| </keyVal>
| </sublevel>
| <sublevel id='2'>
| <keyVal>
| <key>anotherKey</key>
| <value>42</value>
| </keyVal>
| <keyVal>
| <key>mykey</key>
| <value>fizzbuzz</value>
| </keyVal>
| </sublevel>
| </level>
| </root>
"""
root = ().parseText(xmlText.stripMargin())
root.level.size() == 1 1
root.level.sublevel.size() == 2 2
root.level.sublevel.findAll { it.@id == 1 }.size() == 1 3
root.level.sublevel[1].keyVal[0].key.text() == 'anotherKey' 4
Number promotion
The rules of number promotion are speci ed in the section on math operations.
Functional interfaces
<T> {
accept(T obj)
}
{
getName()
greet() {
println "Hello, $name"
}
}
Any closure can be converted into a SAM type using the as operator:
http://docs.groovy-lang.org/latest/html/documentation/ 116/502
1/6/2019 Groovy Language Documentation
filter = { it.contains 'G' }
filter.accept('Groovy') ==
greeter = { 'Groovy' }
greeter.greet()
However, the as Type expression is optional since Groovy 2.2.0. You can omit it and simply write:
greeter = { 'Groovy' }
greeter.greet()
which means you are also allowed to use method pointers, as shown in the following example:
doFilter( s) { s.contains('G') }
filter = .&doFilter
filter.accept('Groovy') ==
greeter = .&getVersion
greeter.greet()
Then you can call it with a closure, without having to create an explicit implementation of the interface:
But since Groovy 2.2.0, you are also able to omit the explicit coercion and call the method as if it used a closure:
As you can see, this has the advantage of letting you use the closure syntax for method calls, that is to say put the closure outside
of the parenthesis, improving the readability of your code.
{
foo()
bar()
}
You can coerce a closure into the interface using the as keyword:
This produces a class for which all methods are implemented using the closure:
impl.foo() == 123
impl.bar()
http://docs.groovy-lang.org/latest/html/documentation/ 117/502
1/6/2019 But it is also possible to coerce a closure to any class. For Groovy
example, we can replace
Language the interface that we de ned with class
Documentation
without changing the assertions:
{
foo() { 1 }
bar() { println 'bar' }
}
impl.foo() == 123
impl.bar()
map
map = [
i: 10,
hasNext: { map.i > 0 },
: { map.i-- },
]
iter = map
Of course this is a rather contrived example, but illustrates the concept. You only need to implement those methods that are
actually called, but if a method is called that doesn’t exist in the map a MissingMethodException or an
UnsupportedOperationException is thrown, depending on the arguments passed to the call, as in the following example:
X {
f()
g( n)
h( s, n)
}
MissingMethodException if the arguments of the call do not match those from the interface/class
UnsupportedOperationException if the arguments of the call match one of the overloaded methods of the interface/class
{
up,
down
}
then you can assign a string to the enum without having to use an explicit as coercion:
st = 'up'
st == .up
http://docs.groovy-lang.org/latest/html/documentation/ 118/502
1/6/2019 Groovy Language Documentation
val = "up"
st = "${val}"
st == .up
switchState( st) {
(st) {
'up':
.down // explicit constant
'down':
'up' // implicit coercion for return types
}
}
in particular, see how the case use string constants. But if you call a method that uses an enum with a String argument, you
still have to use an explicit as coercion:
switchState('up' ) == .down
switchState( .down) == .up
{
r
phi
}
{
x
y
}
And that you want to convert from polar coordinates to cartesian coordinates. One way of doing this is to de ne the asType
method in the Polar class:
asType( target) {
( ==target) {
(x: r*cos(phi), y: r*sin(phi))
}
}
sigma = 1E-16
polar = (r:1.0,phi:PI/2)
cartesian = polar
abs(cartesian.x-sigma) < sigma
http://docs.groovy-lang.org/latest/html/documentation/ 119/502
1/6/2019 Groovy Language Documentation
{
r
phi
asType( target) {
( ==target) {
(x: r*cos(phi), y: r*sin(phi))
}
}
}
but it is also possible to de ne asType outside of the Polar class, which can be practical if you want to de ne custom coercion
strategies for "closed" classes or classes for which you don’t own the source code, for example using a metaclass:
{
greet()
}
greeter = { println 'Hello, Groovy!' } // Greeter is known statically
greeter.greet()
But what if you get the class by re ection, for example by calling Class.forName ?
clazz = .forName('Greeter')
Trying to use the reference to the class with the as keyword would fail:
It is failing because the as keyword only works with class literals. Instead, you need to call the asType method:
1.6.4. Optionality
Optional parentheses
Method calls can omit the parentheses if there is at least one parameter and there is no ambiguity:
Parentheses are required for method calls without parameters or ambiguous method calls:
println()
println( .max(5, 10))
Optional semicolons
In Groovy semicolons at the end of the line can be omitted, if the line contains only a single statement.
http://docs.groovy-lang.org/latest/html/documentation/ 120/502
1/6/2019 This means that: Groovy Language Documentation
a = ; a
add( a, b) {
a+b
}
add(1, 2) == 3
add( a, b) {
a+b
}
add(1, 2) == 3
{
toString() { "a server" }
}
{
toString() { "a server" }
}
Boolean expressions
True if the corresponding Boolean value is true .
[1, 2, 3]
![]
Matchers
http://docs.groovy-lang.org/latest/html/documentation/ 121/502
1/6/2019 True if the Matcher has at least one match. Groovy Language Documentation
('a' =~ /a/)
!('a' =~ /b/)
[0].iterator()
![].iterator()
v = [0]
enumeration = v.elements()
enumeration
enumeration.nextElement()
!enumeration
Maps
Non-empty Maps are evaluated to true.
['one' : 1]
![:]
Strings
Non-empty Strings, GStrings and CharSequences are coerced to true.
'a'
!''
nonEmpty = 'a'
"$nonEmpty"
empty = ''
!"$empty"
Numbers
Non-zero numbers are true.
1
3.5
!0
Object References
Non-null object references are coerced to true.
()
!
{
name
asBoolean(){
name == 'green' ? :
}
}
Groovy will call this method to coerce your object to a boolean value, e.g.:
http://docs.groovy-lang.org/latest/html/documentation/ 122/502
1/6/2019 Groovy Language Documentation
(name: 'green')
! (name: 'red')
1.6.6. Typing
Optional typing
Optional typing is the idea that a program can work even if you don’t put an explicit type on a variable. Being a dynamic language,
Groovy naturally implements that feature, for example when you declare a variable:
aString = 'foo' 1
aString.toUpperCase() 2
aString = 'foo' 1
aString.toUpperCase() 2
So it doesn’t matter that you use an explicit type here. It is in particular interesting when you combine this feature with static type
checking, because the type checker performs type inference.
Likewise, Groovy doesn’t make it mandatory to declare the types of a parameter in a method:
concat( a, b) {
a+b
}
concat('foo','bar') == 'foobar'
can be rewritten using def as both return type and parameter types, in order to take advantage of duck typing, as illustrated in
this example:
concat( a, b) { 1
a+b
}
concat('foo','bar') == 'foobar' 2
concat(1,2) == 3 3
1 both the return type and the parameter types use def
2 it makes it possible to use the method with String
3 but also with int since the plus method is de ned
Using the def keyword here is recommended to describe the intent of a method which is supposed to work on
any type, but technically, we could use Object instead and the result would be the same: def is, in Groovy,
strictly equivalent to using Object .
Eventually, the type can be removed altogether from both the return type and the descriptor. But if you want to remove it from
the return type, you then need to add an explicit modi er for the method, so that the compiler can make a di erence between a
method declaration and a method call, like illustrated in this example:
concat(a,b) { 1
a+b
}
concat('foo','bar') == 'foobar' 2
concat(1,2) == 3
http://docs.groovy-lang.org/latest/html/documentation/
3
123/502
1/6/2019 1 if we want to omit the return type, an explicit modi Groovy Language
er has to be set. Documentation
2 it is still possible to use the method with String
3 and also with int
Omitting types is in general considered a bad practice in method parameters or method return types for public
APIs. While using def in a local variable is not really a problem because the visibility of the variable is limited to
the method itself, while set on a method parameter, def will be converted to Object in the method signature,
making it di cult for users to know which is the expected type of the arguments. This means that you should limit
this to cases where you are explicitly relying on duck typing.
{ 1
firstName
lastName
}
p = (firstName: 'Raymond', lastName: 'Devos') 2
1 the Person class only de nes two properties, firstName and lastName
2 we can create an instance of Person
3 and call a method named formattedName
It is quite common in dynamic languages for code such as the above example not to throw any error. How can this be? In Java, this
would typically fail at compile time. However, in Groovy, it will not fail at compile time, and if coded correctly, will also not fail at
runtime. In fact, to make this work at runtime, one possibility is to rely on runtime metaprogramming. So just adding this line after
the declaration of the Person class is enough:
This means that in general, in Groovy, you can’t make any assumption about the type of an object beyond its declaration type, and
even if you know it, you can’t determine at compile time what method will be called, or which property will be retrieved. It has a lot
of interest, going from writing DSLs to testing, which is discussed in other sections of this manual.
However, if your program doesn’t rely on dynamic features and that you come from the static world (in particular, from a Java
mindset), not catching such "errors" at compile time can be surprising. As we have seen in the previous example, the compiler
cannot be sure this is an error. To make it aware that it is, you have to explicitly instruct the compiler that you are switching to a
type checked mode. This can be done by annotating a class or a method with @groovy.lang.TypeChecked .
When type checking is activated, the compiler performs much more work:
type inference is activated, meaning that even if you use def on a local variable for example, the type checker will be able to
infer the type of the variable from the assignments
method calls are resolved at compile time, meaning that if a method is not declared on a class, the compiler will throw an error
in general, all the compile time errors that you are used to nd in a static language will appear: method not found, property
not found, incompatible types for method calls, number precision errors, …
In this section, we will describe the behavior of the type checker in various situations and explain the limits of using
@TypeChecked on your code.
http://docs.groovy-lang.org/latest/html/documentation/ 124/502
1/6/2019 Groovy Language Documentation
@groovy.transform.
{
sum( x, y) { x+y }
}
Or on a method:
{
@groovy.transform.
sum( x, y) { x+y }
}
In the rst case, all methods, properties, elds, inner classes, … of the annotated class will be type checked, whereas in the second
case, only the method and potential closures or anonymous inner classes that it contains will be type checked.
Skipping sections
The scope of type checking can be restricted. For example, if a class is type checked, you can instruct the type checker to skip a
method by annotating it with @TypeChecked(TypeCheckingMode.SKIP) :
groovy.transform.
groovy.transform.
@TypeChecked 1
{
greeting() { 2
doGreet()
}
@TypeChecked( .SKIP) 3
doGreet() {
b = ()
b. . .name. . 4
b
}
}
s = ()
s.greeting() == 'Hello my name is John'
In the previous example, SentenceBuilder relies on dynamic code. There’s no real Hello method or property, so the type
checker would normally complain and compilation would fail. Since the method that uses the builder is marked with
TypeCheckingMode.SKIP , type checking is skipped for this method, so the code will compile, even if the rest of the class is type
checked.
T equals A
now = ()
http://docs.groovy-lang.org/latest/html/documentation/ 125/502
1/6/2019 Groovy Language Documentation
s = // passes
i = // fails
or T is an array and A is an array and the component type of A is assignable to the component type of T
[] i = [4] // passes
[] i = [4] // fails
or T is an array and A is a list and the component type of A is assignable to the component type of T
[] i = [1,2,3] // passes
[] i = [1,2, ()] // fails
or T is a superclass of A
list = () // passes
list = () // fails
or T is an interface implemented by A
list = () // passes
list = () // fails
i = 0
bi = 1
x = (123)
d = (5f)
http://docs.groovy-lang.org/latest/html/documentation/ 126/502
1/6/2019 Groovy Language Documentation
r = { println 'Hello' }
{
doSomething()
}
sam = { 123 }
sam.doSomething() == 123
{
calc() { 2* value() }
value()
}
c = { 123 }
c.calc() == 246
T A Examples
Byte Byte
b1 = ( ) 4
the assignment is a variable declaration and A is a list literal and T has a constructor whose parameters match the types of
the elements in the list literal
http://docs.groovy-lang.org/latest/html/documentation/ 127/502
1/6/2019 the assignment is a variable declaration and A is a map literalLanguage
Groovy and T has a no-arg constructor and a property for each of the
Documentation
map keys
@groovy.transform.
{
firstName
lastName
}
classic = ('Ada','Lovelace')
list = ['Ada','Lovelace']
or a "map constructor":
If you use a map constructor, additional checks are done on the keys of the map to check if a property of the same name is
de ned. For example, the following will fail at compile time:
@groovy.transform.
{
firstName
lastName
}
map = [firstName:'Ada', lastName:'Lovelace', age: 24] 1
1 The type checker will throw an error No such property: age for class: Person at compile time
Method resolution
In type checked mode, methods are resolved at compile time. Resolution works by name and arguments. The return type is
irrelevant to method selection. Types of arguments are matched against the types of the parameters following those rules:
An argument o of type A can be used for a parameter of type T if and only if:
T equals A
sum( x, y) {
x+y
}
sum(3,4) == 7
format( str) {
"Result: $str"
}
format("${3+4}") == "Result: 7"
http://docs.groovy-lang.org/latest/html/documentation/ 128/502
1/6/2019 Groovy Language Documentation
format( value) {
"Result: $value"
}
format(7) == "Result: 7"
format( ) // fails
or T is an array and A is an array and the component type of A is assignable to the component type of T
format( [] values) {
"Result: ${values.join(' ')}"
}
format(['a','b'] []) == "Result: a b"
format([1,2] []) // fails
or T is a superclass of A
format( list) {
list.join(',')
}
format( ()) // passes
format( list) {
list.join(',')
}
format( ()) // fails
or T is an interface implemented by A
format( list) {
list.join(',')
}
format( ()) // passes
format( list) {
'foo'
}
format( ()) // fails
sum( x, y) {
x+y
}
sum(3, (4)) == 7
sum( (3), 4) == 7
sum( (3), (4)) == 7
sum( (3), 4) == 7
http://docs.groovy-lang.org/latest/html/documentation/ 129/502
1/6/2019 Groovy Language Documentation
{
doSomething()
}
twice( sam) { 2*sam.doSomething() }
twice { 123 } == 246
{
calc() { 2* value() }
value()
}
eightTimes( sam) { 4*sam.calc() }
eightTimes { 123 } == 984
or T and A derive from java.lang.Number and conform to the same rules as assignment of numbers
If a method with the appropriate name and arguments is not found at compile time, an error is thrown. The di erence with
"normal" Groovy is illustrated in the following example:
{
doSomething() {
printLine 'Do something' 1
}
}
1 printLine is an error, but since we’re in a dynamic mode, the error is not caught at compile time
The example above shows a class that Groovy will be able to compile. However, if you try to create an instance of MyService and
call the doSomething method, then it will fail at runtime, because printLine doesn’t exist. Of course, we already showed how
Groovy could make this a perfectly valid call, for example by catching MethodMissingException or implementing a custom
meta-class, but if you know you’re not in such a case, @TypeChecked comes handy:
@groovy.transform.
{
doSomething() {
printLine 'Do something' 1
}
}
Just adding @TypeChecked will trigger compile time method resolution. The type checker will try to nd a method printLine
accepting a String on the MyService class, but cannot nd one. It will fail compilation with the following message:
It is important to understand the logic behind the type checker: it is a compile-time check, so by de nition,
the type checker is not aware of any kind of runtime metaprogramming that you do. This means that code
which is perfectly valid without @TypeChecked will not compile anymore if you activate type checking. This
is in particular true if you think of duck typing:
http://docs.groovy-lang.org/latest/html/documentation/ 130/502
1/6/2019 Groovy Language Documentation
{
quack() { 1
println 'Quack!'
}
}
{
quack() { 2
println 'Quack!'
}
}
@groovy.transform.
accept(quacker) {
quacker.quack() 3
}
accept( ()) 4
There are possible workarounds, like introducing an interface, but basically, by activating type checking, you gain type safety
but you loose some features of the language. Hopefully, Groovy introduces some features like ow typing to reduce the gap
between type-checked and non type-checked Groovy.
Type inference
Principles
When code is annotated with @TypeChecked , the compiler performs type inference. It doesn’t simply rely on static types, but also
uses various techniques to infer the types of variables, return types, literals, … so that the code remains as clean as possible even
if you activate the type checker.
println message.toUpperCase() 2
The reason the call to toUpperCase works is because the type of message was inferred as being a String .
http://docs.groovy-lang.org/latest/html/documentation/ 131/502
1/6/2019 Groovy Language Documentation
{
someUntypedField 1
someTypedField 2
someMethod() {
someUntypedField = '123' 3
someSafeMethod() {
someTypedField = '123' 5
someTypedField = someTypedField.toUpperCase() 6
someMethodUsingLocalVariable() {
localVariable = '123' 7
someUntypedField = localVariable.toUpperCase() 8
}
}
Why such a di erence? The reason is thread safety. At compile time, we can’t make any guarantee about the type of a eld. Any
thread can access any eld at any time and between the moment a eld is assigned a variable of some type in a method and the
time is is used the line after, another thread may have changed the contents of the eld. This is not the case for local variables: we
know if they "escape" or not, so we can make sure that the type of a variable is constant (or not) over time. Note that even if a eld
is nal, the JVM makes no guarantee about it, so the type checker doesn’t behave di erently if a eld is nal or not.
This is one of the reasons why we recommend to use typed elds. While using def for local variables is perfectly
ne thanks to type inference, this is not the case for elds, which also belong to the public API of a class, hence the
type is important.
The inferred type of a literal depends on the elements of the literal, as illustrated in the following table:
java.util.List
list = []
java.util.List<String>
list = ['foo','bar']
http://docs.groovy-lang.org/latest/html/documentation/ 132/502
1/6/2019 Groovy Language Documentation
Literal Inferred type
java.util.LinkedHashMap
map = [:]
java.util.LinkedHashMap<String,String>
map1 = [someKey: 'someValue']
map2 = ['someKey': 'someValue']
groovy.lang.IntRange
intRange = (0..10)
As you can see, with the noticeable exception of the IntRange , the inferred type makes use of generics types to describe the
contents of a collection. In case the collection contains elements of di erent types, the type checker still performs type inference
of the components, but uses the notion of least upper bound.
if A or B is a primitive type and that A isn’t equal to B , the least upper bound of A and B is the least upper bound of their
wrapper types
If A and B only have one (1) interface in common and that their common superclass is Object , then the LUB of both is the
common interface.
The least upper bound represents the minimal type to which both A and B can be assigned. So for example, if A and B are both
String , then the LUB (least upper bound) of both is also String .
{}
{}
{}
leastUpperBound( , ) == 1
leastUpperBound( , ) == 2
leastUpperBound( , ) == 3
leastUpperBound( , ) == 4
leastUpperBound( , ) == 5
leastUpperBound( , ) == 6
http://docs.groovy-lang.org/latest/html/documentation/ 133/502
1/6/2019 In those examples, the LUB is always representable as a normal,
Groovy JVM supported,
Language type. But Groovy internally represents the LUB as
Documentation
a type which can be more complex, and that you wouldn’t be able to use to de ne a variable for example. To illustrate this, let’s
continue with this example:
{}
{}
, {}
, {}
What is the least upper bound of Bottom and SerializableFooImpl ? They don’t have a common super class (apart from
Object ), but they do share 2 interfaces ( Serializable and Foo ), so their least upper bound is a type which represents the
union of two interfaces ( Serializable and Foo ). This type cannot be de ned in the source code, yet Groovy knows about it.
In the context of collection type inference (and generic type inference in general), this becomes handy, because the type of the
components is inferred as the least upper bound. We can illustrate why this is important in the following example:
{ greet() } 1
{ salute() } 2
A , { 3
}
list = [ A(), B()] 6
list.each {
it.greet() 7
it.salute() 8
it. () 9
which indicates that the exit method is neither de nes on Greeter nor Salute , which are the two interfaces de ned in the
least upper bound of A and B .
instanceof inference
In normal, non type checked, Groovy, you can write things like:
http://docs.groovy-lang.org/latest/html/documentation/ 134/502
1/6/2019 Groovy Language Documentation
{
greeting() { 'Hello' }
}
doSomething( o) {
(o ) { 1
println o.greeting() 2
}
}
doSomething( ())
The method call works because of dynamic dispatch (the method is selected at runtime). The equivalent code in Java would
require to cast o to a Greeter before calling the greeting method, because methods are selected at compile time:
(o ) {
. .println((( )o).greeting());
}
However, in Groovy, even if you add @TypeChecked (and thus activate type checking) on the doSomething method, the cast is
not necessary. The compiler embeds instanceof inference that makes the cast optional.
Flow typing
Flow typing is an important concept of Groovy in type checked mode and an extension of type inference. The idea is that the
compiler is capable of inferring the type of variables in the ow of the code, not just at initialization:
@groovy.transform.
flowTyping() {
o = 'foo' 1
o = o.toUpperCase() 2
o = 9d 3
o = .sqrt(o) 4
So the type checker is aware of the fact that the concrete type of a variable is di erent over time. In particular, if you replace the
last assignment with:
o = 9d
o = o.toUpperCase()
The type checker will now fail at compile time, because it knows that o is a double when toUpperCase is called, so it’s a type
error.
It is important to understand that it is not the fact of declaring a variable with def that triggers type inference. Flow typing works
for any variable of any type. Declaring a variable with an explicit type only constrains what you can assign to the variable:
@groovy.transform.
flowTypingWithExplicitType() {
list = ['a','b','c'] 1
list = list*.toUpperCase() 2
list = 'foo' 3
}
http://docs.groovy-lang.org/latest/html/documentation/ 135/502
1/6/2019 1 Groovy
list is declared as an unchecked List and assigned Language
a list literal ofDocumentation
`String`s
2 this line passes compilation because of ow typing: the type checker knows that list is at this point a List<String>
3 but you can’t assign a String to a List so this is a type checking error
You can also note that even if the variable is declared without generics information, the type checker knows what is the
component type. Therefore, such code would fail compilation:
@groovy.transform.
flowTypingWithExplicitType() {
list = ['a','b','c'] 1
list.add(1) 2
@groovy.transform.
flowTypingWithExplicitType() {
<? > list = [] 1
list.addAll(['a','b','c']) 2
list.add(1) 3
1 list declared as List<? extends Serializable> and initialized with an empty list
2 elements added to the list conform to the declaration type of the list
3 so adding an int to a List<? extends Serializable> is allowed
Flow typing has been introduced to reduce the di erence in semantics between classic and static Groovy. In particular, consider
the behavior of this code in Java:
compute( str) {
str.length();
}
compute( o) {
"Nope";
}
// ...
string = "Some string"; 1
result = compute(string); 2
.out.println(result); 3
In Java, this code will output Nope , because method selection is done at compile time and based on the declared types. So even if
o is a String at runtime, it is still the Object version which is called, because o has been declared as an Object . To be short,
in Java, declared types are most important, be it variable types, parameter types or return types.
compute( ) { .length() }
compute( o) { "Nope" }
o = 'string'
result = compute(o)
println result
http://docs.groovy-lang.org/latest/html/documentation/ 136/502
1/6/2019 But this time, it will return 6 , because the method which Groovy
is chosen is chosen
Language at runtime, based on the actual argument types. So
Documentation
at runtime, o is a String so the String variant is used. Note that this behavior has nothing to do with type checking, it’s the
way Groovy works in general: dynamic dispatch.
In type checked Groovy, we want to make sure the type checker selects the same method at compile time, that the runtime would
choose. It is not possible in general, due to the semantics of the language, but we can make things better with ow typing. With
ow typing, o is inferred as a String when the compute method is called, so the version which takes a String and returns an
int is chosen. This means that we can infer the return type of the method to be an int , and not a String . This is important for
subsequent calls and type safety.
So in type checked Groovy, ow typing is a very important concept, which also implies that if @TypeChecked is applied, methods
are selected based on the inferred types of the arguments, not on the declared types. This doesn’t ensure 100% type safety,
because the type checker may select a wrong method, but it ensures the closest semantics to dynamic Groovy.
{
methodFromTop() {}
}
{
methodFromBottom() {}
}
o
(someCondition) {
o = () 1
} {
o = () 2
}
o.methodFromTop() 3
When the type checker visits an if/else control structure, it checks all variables which are assigned in if/else branches and
computes the least upper bound of all assignments. This type is the type of the inferred variable after the if/else block, so in
this example, o is assigned a Top in the if branch and a Bottom in the else branch. The LUB of those is a Top , so after the
conditional branches, the compiler infers o as being a Top . Calling methodFromTop will therefore be allowed, but not
methodFromBottom .
The same reasoning exists with closures and in particular closure shared variables. A closure shared variable is a variable which is
de ned outside of a closure, but used inside a closure, as in this example:
closure = {
println text 2
Groovy allows developers to use those variables without requiring them to be nal. This means that a closure shared variable can
be reassigned inside a closure:
http://docs.groovy-lang.org/latest/html/documentation/ 137/502
1/6/2019 Groovy Language Documentation
result
doSomething { it ->
result = "Result: $it"
}
result = result?.toUpperCase()
The problem is that a closure is an independent block of code that can be executed (or not) at any time. In particular,
doSomething may be asynchronous, for example. This means that the body of a closure doesn’t belong to the main control ow.
For that reason, the type checker also computes, for each closure shared variable, the LUB of all assignments of the variable, and
will use that LUB as the inferred type outside of the scope of the closure, like in this example:
{
methodFromTop() {}
}
{
methodFromBottom() {}
}
o = () 1
.start {
o = () 2
}
o.methodFromTop() 3
Here, it is clear that when methodFromBottom is called, there’s no guarantee, at compile-time or runtime that the type of o will
e ectively be a Bottom . There are chances that it will be, but we can’t make sure, because it’s asynchronous. So the type checker
will only allow calls on the least upper bound, which is here a Top .
@groovy.transform.
testClosureReturnTypeInference( arg) {
cl = { "Arg: $arg" } 1
val = cl() 2
val.length() 3
As you can see, unlike a method which declares its return type explicitly, there’s no need to declare the return type of a closure: its
type is inferred from the body of the closure.
Closures vs methods
http://docs.groovy-lang.org/latest/html/documentation/ 138/502
1/6/2019 It’s worth noting that return type inference is only applicable
GroovytoLanguage
closures.Documentation
While the type checker could do the same on a
method, it is in practice not desirable: in general, methods can be overridden and it is not statically possible to make sure
that the method which is called is not an overridden version. So ow typing would actually think that a method returns
something, while in reality, it could return something else, like illustrated in the following example:
@TypeChecked
A {
compute() { 'some string' } 1
computeFully() {
compute().toUpperCase() 2
}
}
@TypeChecked
B A {
compute() { 123 } 3
As you can see, if the type checker relied on the inferred return type of a method, with ow typing, the type checker could
determine that it is ok to call toUpperCase . It is in fact an error, because a subclass can override compute and return a
di erent object. Here, B#compute returns an int , so someone calling computeFully on an instance of B would see a
runtime error. The compiler prevents this from happening by using the declared return type of methods instead of the
inferred return type.
For consistency, this behavior is the same for every method, even if they are static or nal.
To illustrate this, lets start with an example that will fail compilation due to the inability for the type checker to infer the parameter
types:
{
name
age
}
(predicate.call(p)) {
// send invite
// ...
}
}
@groovy.transform.
failCompilation() {
p = (name: 'Gerard', age: 55)
inviteIf(p) { 2
}
}
http://docs.groovy-lang.org/latest/html/documentation/ 139/502
1/6/2019 3 Groovy
yet it is not statically known as being a Person and Language
compilation Documentation
fails
In this example, the closure body contains it.age . With dynamic, not type checked code, this would work, because the type of
it would be a Person at runtime. Unfortunately, at compile-time, there’s no way to know what is the type of it , just by reading
the signature of inviteIf .
inviteIf(p) { it -> 1
it.age >= 18
}
By explicitly declaring the type of the it variable, you can workaround the problem and make this code statically checked.
(predicate.apply(p)) {
// send invite
// ...
}
}
@groovy.transform.
passesCompilation() {
p = (name: 'Gerard', age: 55)
inviteIf(p) { 3
it.age >= 18 4
}
}
By using this technique, we leverage the automatic coercion of closures to SAM types feature of Groovy. The
question whether you should use a SAM type or a Closure really depends on what you need to do. In a lot of
cases, using a SAM interface is enough, especially if you consider functional interfaces as they are found in Java 8.
However, closures provide features that are not accessible to functional interfaces. In particular, closures can have
a delegate, and owner and can be manipulated as objects (for example, cloned, serialized, curried, …) before being
called. They can also support multiple signatures (polymorphism). So if you need that kind of manipulation, it is
preferable to switch to the most advanced type inference annotations which are described below.
The original issue that needs to be solved when it comes to closure parameter type inference, that is to say, statically determining
the types of the arguments of a closure without having to have them explicitly declared, is that the Groovy type system inherits
the Java type system, which is insu cient to describe the types of the arguments.
http://docs.groovy-lang.org/latest/html/documentation/ 140/502
1/6/2019 Let’s illustrate this by xing the original example, introducing the Language
Groovy @ClosureParams annotation:
Documentation
groovy.transform.stc.
groovy.transform.stc.
inviteIf( p, @ClosureParams( ) < > predicate) { 1
(predicate.call(p)) {
// send invite
// ...
}
}
inviteIf(p) { 2
it.age >= 18
}
The @ClosureParams annotation minimally accepts one argument, which is named a type hint. A type hint is a class which is
responsible for completing type information at compile time for the closure. In this example, the type hint being used is
groovy.transform.stc.FirstParam which indicated to the type checker that the closure will accept one parameter whose type
is the type of the rst parameter of the method. In this case, the rst parameter of the method is Person , so it indicates to the
type checker that the rst parameter of the closure is in fact a Person .
A second optional argument is named options. It’s semantics depend on the type hint class. Groovy comes with various bundled
type hints, illustrated in the table below:
FirstParam No The rst (resp. second, third) parameter type of the method
SecondParam
ThirdParam groovy.transform.stc.
doSomething( str, @ClosureParams( )
c) {
c(str)
}
doSomething('foo') { println it.toUpperCase() }
groovy.transform.stc.
withHash( str, seed,
@ClosureParams( ) c) {
c(31*str.hashCode()+seed)
}
withHash('foo', ( ) .currentTimeMillis()) {
mod = it%2
}
groovy.transform.stc.
format( prefix, postfix, o,
@ClosureParams( ) c) {
"$prefix${c(o)}$postfix"
}
format('foo', 'bar', 'baz') {
it.toUpperCase()
} == 'fooBAZbar'
http://docs.groovy-lang.org/latest/html/documentation/ 141/502
1/6/2019 Groovy Language Documentation
Type hint Polymorphic? Description and examples
FirstParam.FirstGenericType No The rst generic type of the rst (resp. second, third) parameter of the
SecondParam.FirstGenericType method
ThirdParam.FirstGenericType
groovy.transform.stc.
<T> doSomething( <T> strings,
@ClosureParams( . ) c) {
strings.each {
c(it)
}
}
doSomething(['foo','bar']) { println it.toUpperCase() }
doSomething([1,2,3]) { println(2*it) }
SimpleType No A type hint for which the type of closure parameters comes from the
options string.
groovy.transform.stc.
doSomething(@ClosureParams(value= ,options=
['java.lang.String','int']) c) {
c('foo',3)
}
doSomething { str, len ->
str.length() == len
}
This type hint supports a single signature and each of the parameter is
speci ed as a value of the options array using a fully-quali ed type name
or a primitive type.
MapEntryOrKeyValue Yes A dedicated type hint for closures that either work on a Map.Entry single
parameter, or two parameters corresponding to the key and the value.
groovy.transform.stc.
<K,V> doSomething( <K,V> map,
@ClosureParams( ) c) {
// ...
}
doSomething([a: 'A']) { k,v ->
k.toUpperCase() == v.toUpperCase()
}
doSomething([abc: 3]) { e ->
e.key.length() == e.value
}
This type hint requires that the rst argument is a Map type, and infers
the closure parameter types from the map actual key/value types.
http://docs.groovy-lang.org/latest/html/documentation/ 142/502
1/6/2019 Groovy Language Documentation
Type hint Polymorphic? Description and examples
FromAbstractTypeMethods Yes Infers closure parameter types from the abstract method of some type. A
signature is inferred for each abstract method.
groovy.transform.stc.
{
firstSignature( x, y)
secondSignature( str)
}
doSomething(@ClosureParams(value= ,
options=["Foo"]) cl) {
// ...
}
doSomething { a, b -> a+b }
doSomething { s -> s.toUpperCase() }
If there are multiple signatures like in the example above, the type
checker will only be able to infer the types of the arguments if the arity of
each method is di erent. In the example above, firstSignature takes 2
arguments and secondSignature takes 1 argument, so the type checker
can infer the argument types based on the number of arguments. But see
the optional resolver class attribute discussed next.
http://docs.groovy-lang.org/latest/html/documentation/ 143/502
1/6/2019 Groovy Language Documentation
Type hint Polymorphic? Description and examples
FromString Yes Infers the closure parameter types from the options argument. The
options argument consists of an array of comma-separated non-
primitive types. Each element of the array corresponds to a single
signature, and each comma in an element separate parameters of the
signature. In short, this is the most generic type hint, and each string of
the options map is parsed as if it was a signature literal. While being
very powerful, this type hint must be avoided if you can because it
increases the compilation times due to the necessity of parsing the type
signatures.
groovy.transform.stc.
doSomething(@ClosureParams(value= ,
options=["String","String,Integer"]) cl) {
// ...
}
doSomething { s -> s.toUpperCase() }
doSomething { s,i -> s.toUpperCase()*i }
groovy.transform.stc.
doSomething(@ClosureParams(value= ,
options=["String","String,Integer"]) cl) {
// ...
}
doSomething { s -> s.toUpperCase() }
doSomething { s,i -> s.toUpperCase()*i }
groovy.transform.stc.
<T> doSomething(T e,
@ClosureParams(value= , options=["T","T,T"])
cl) {
// ...
}
doSomething('foo') { s -> s.toUpperCase() }
doSomething('foo') { s1,s2 -> s1.toUpperCase()
== s2.toUpperCase() }
Even though you use FirstParam , SecondParam or ThirdParam as a type hint, it doesn’t strictly mean that the
argument which will be passed to the closure will be the rst (resp. second, third) argument of the method call. It
only means that the type of the parameter of the closure will be the same as the type of the rst (resp. second,
third) argument of the method call.
In short, the lack of the @ClosureParams annotation on a method accepting a Closure will not fail compilation. If present (and it
can be present in Java sources as well as Groovy sources), then the type checker has more information and can perform
additional type inference. This makes this feature particularly interesting for framework developers.
A third optional argument is named con ictResolutionStrategy. It can reference a class (extending from
ClosureSignatureConflictResolver ) that can perform additional resolution of parameter types if more than one are found
after initial inference calculations are complete. Groovy comes with the a default type resolver which does nothing, and another
which selects the rst signature if multiple are found. The resolver is only invoked if more than one signature is found and is by
design a post processor. Any statements which need injected typing information must pass one of the parameter signatures
determined through type hints. The resolver then picks among the returned candidate signatures.
http://docs.groovy-lang.org/latest/html/documentation/ 144/502
1/6/2019 @DelegatesTo Groovy Language Documentation
The @DelegatesTo annotation is used by the type checker to infer the type of the delegate. It allows the API designer to instruct
the compiler what is the type of the delegate and the delegation strategy. The @DelegatesTo annotation is discussed in a speci c
section (core-domain-speci c-languages.html#section-delegatesto).
Static compilation
Dynamic vs static
In the type checking section, we have seen that Groovy provides optional type checking thanks to the @TypeChecked annotation.
The type checker runs at compile time and performs a static analysis of dynamic code. The program will behave exactly the same
whether type checking has been enabled or not. This means that the @TypeChecked annotation is neutral with regards to the
semantics of a program. Even though it may be necessary to add type information in the sources so that the program is
considered type safe, in the end, the semantics of the program are the same.
While this may sound ne, there is actually one issue with this: type checking of dynamic code, done at compile time, is by
de nition only correct if no runtime speci c behavior occurs. For example, the following program passes type checking:
{
compute( str) {
str.length()
}
compute( x) {
.valueOf(x)
}
}
@groovy.transform.
test() {
computer = ()
computer. {
compute(compute('foobar')) =='6'
}
}
There are two compute methods. One accepts a String and returns an int , the other accepts an int and returns a String .
If you compile this, it is considered type safe: the inner compute('foobar') call will return an int , and calling compute on this
int will in turn return a String .
Using runtime metaprogramming, we’re actually modifying the behavior of the compute(String) method, so that instead of
returning the length of the provided argument, it will return a Date . If you execute the program, it will fail at runtime. Since this
line can be added from anywhere, in any thread, there’s absolutely no way for the type checker to statically make sure that no
such thing happens. In short, the type checker is vulnerable to monkey patching. This is just one example, but this illustrates the
concept that doing static analysis of a dynamic program is inherently wrong.
The Groovy language provides an alternative annotation to @TypeChecked which will actually make sure that the methods which
are inferred as being called will e ectively be called at runtime. This annotation turns the Groovy compiler into a static compiler,
where all method calls are resolved at compile time and the generated bytecode makes sure that this happens: the annotation is
@groovy.transform.CompileStatic .
Let’s take the example which failed, but this time let’s replace the @TypeChecked annotation with @CompileStatic :
http://docs.groovy-lang.org/latest/html/documentation/ 145/502
1/6/2019 Groovy Language Documentation
{
compute( str) {
str.length()
}
compute( x) {
.valueOf(x)
}
}
@groovy.transform.
test() {
computer = ()
computer. {
compute(compute('foobar')) =='6'
}
}
.metaClass.compute = { str -> () }
test()
This is the only di erence. If we execute this program, this time, there is no runtime error. The test method became immune to
monkey patching, because the compute methods which are called in its body are linked at compile time, so even if the metaclass
of Computer changes, the program still behaves as expected by the type checker.
Key bene ts
There are several bene ts of using @CompileStatic on your code:
type safety
performance improvements
The performance improvements depend on the kind of program you are executing. If it is I/O bound, the di erence between
statically compiled code and dynamic code is barely noticeable. On highly CPU intensive code, since the bytecode which is
generated is very close, if not equal, to the one that Java would produce for an equivalent program, the performance is greatly
improved.
Using the invokedynamic version of Groovy, which is accessible to people using JDK 7 and above, the performance
of the dynamic code should be very close to the performance of statically compiled code. Sometimes, it can even
be faster! There is only one way to determine which version you should choose: measuring. The reason is that
depending on your program and the JVM that you use, the performance can be signi cantly di erent. In
particular, the invokedynamic version of Groovy is very sensitive to the JVM version in use.
builder = ( )
builder.html {
head {
// ...
}
body {
p 'Hello, world!'
}
}
http://docs.groovy-lang.org/latest/html/documentation/ 146/502
1/6/2019 In the previous example, none of the html , head , body Groovy
or p methods exist.
Language However if you execute the code, it works because
Documentation
Groovy uses dynamic dispatch and converts those method calls at runtime. In this builder, there’s no limitation about the number
of tags that you can use, nor the attributes, which means there is no chance for a type checker to know about all the possible
methods (tags) at compile time, unless you create a builder dedicated to HTML for example.
Groovy is a platform of choice when it comes to implement internal DSLs. The exible syntax, combined with runtime and
compile-time metaprogramming capabilities make Groovy an interesting choice because it allows the programmer to focus on the
DSL rather than on tooling or implementation. Since Groovy DSLs are Groovy code, it’s easy to have IDE support without having to
write a dedicated plugin for example.
In a lot of cases, DSL engines are written in Groovy (or Java) then user code is executed as scripts, meaning that you have some
kind of wrapper on top of user logic. The wrapper may consist, for example, in a GroovyShell or GroovyScriptEngine that
performs some tasks transparently before running the script (adding imports, applying AST transforms, extending a base script,
…). Often, user written scripts come to production without testing because the DSL logic comes to a point where any user may
write code using the DSL syntax. In the end, a user may just ignore that what he writes is actually code. This adds some challenges
for the DSL implementer, such as securing execution of user code or, in this case, early reporting of errors.
For example, imagine a DSL which goal is to drive a rover on Mars remotely. Sending a message to the rover takes around 15
minutes. If the rover executes the script and fails with an error (say a typo), you have two problems:
rst, feedback comes only after 30 minutes (the time needed for the rover to get the script and the time needed to receive the
error)
second, some portion of the script has been executed and you may have to change the xed script signi cantly (implying that
you need to know the current state of the rover…)
Type checking extensions is a mechanism that will allow the developer of a DSL engine to make those scripts safer by applying the
same kind of checks that static type checking allows on regular groovy classes.
The principle, here, is to fail early, that is to say fail compilation of scripts as soon as possible, and if possible provide feedback to
the user (including nice error messages).
In short, the idea behind type checking extensions is to make the compiler aware of all the runtime metaprogramming tricks that
the DSL uses, so that scripts can bene t the same level of compile-time checks as a verbose statically compiled code would have.
We will see that you can go even further by performing checks that a normal type checker wouldn’t do, delivering powerful
compile-time checks for your users.
@TypeChecked(extensions='/path/to/myextension.groovy')
foo() { ...}
In that case, the foo methods would be type checked with the rules of the normal type checker completed by those found in
the myextension.groovy script. Note that while internally the type checker supports multiple mechanisms to implement type
checking extensions (including plain old java code), the recommended way is to use those type checking extension scripts.
Imagine that you have this rover DSL at hand. A user would write:
robot.move 100
http://docs.groovy-lang.org/latest/html/documentation/ 147/502
1/6/2019 If you have a class de ned as such: Groovy Language Documentation
{
move( qt) { }
}
The script can be type checked before being executed using the following script:
config = ()
config.addCompilationCustomizers(
( ) 1
)
shell = (config) 2
robot = ()
shell.setVariable('robot', robot)
shell.evaluate(script) 3
Using the compiler con guration above, we can apply @TypeChecked transparently to the script. In that case, it will fail at compile
time:
Now, we will slightly update the con guration to include the ``extensions'' parameter:
config.addCompilationCustomizers(
(
,
extensions:['robotextension.groovy'])
)
robotextension.groovy
unresolvedVariable { ->
('robot'== .name) {
storeType( , classNodeFor( ))
handled =
}
}
Here, we’re telling the compiler that if an unresolved variable is found and that the name of the variable is robot, then we can
make sure that the type of this variable is Robot .
Events
The type checker sends the following events, to which an extension script can react:
http://docs.groovy-lang.org/latest/html/documentation/ 148/502
1/6/2019 Groovy Language Documentation
Arguments none
Usage
setup {
// this is called before anything
else
}
Called When Called after the type checker completed type checking
Arguments none
Usage
finish {
// this is after completion
// of all type checking
}
Can be used to perform additional checks after the type checker has nished its
job.
Called When Called when the type checker nds an unresolved variable
Usage
unresolvedVariable { ->
('people' == .name) {
storeType( , classNodeFor( ))
handled =
}
}
Called When Called when the type checker cannot nd a property on the receiver
http://docs.groovy-lang.org/latest/html/documentation/ 149/502
1/6/2019 Groovy Language Documentation
Usage
unresolvedProperty { pexp ->
('longueur'==pexp.propertyAsString &&
getType(pexp.objectExpression)==classNodeFor( )) {
storeType(pexp,classNodeFor( ))
handled =
}
}
Called When Called when the type checker cannot nd an attribute on the receiver
Usage
unresolvedAttribute { aex ->
(getType(aex.objectExpression)==classNodeFor( )) {
storeType(aex,classNodeFor( ))
handled =
}
}
Called When Called before the type checker starts type checking a method call
Usage
beforeMethodCall { call ->
(isMethodCallExpression(call)
&& call.methodAsString=='toUpperCase') {
addStaticTypeError('Not allowed',call)
handled =
}
}
Allows you to intercept method calls before the type checker performs its own checks. This is
useful if you want to replace the default type checking with a custom one for a limited scope.
In that case, you must set the handled ag to true, so that the type checker skips its own
checks.
Called When Called once the type checker has nished type checking a method call
http://docs.groovy-lang.org/latest/html/documentation/ 150/502
1/6/2019 Groovy Language Documentation
Usage
afterMethodCall { call ->
(getTargetMethod(call).name=='toUpperCase') {
addStaticTypeError('Not allowed',call)
handled =
}
}
Allow you to perform additional checks after the type checker has done its own checks. This is
in particular useful if you want to perform the standard type checking tests but also want to
ensure additional type safety, for example checking the arguments against each other.Note
that afterMethodCall is called even if you did beforeMethodCall and set the handled ag
to true.
Called When Called by the type checker when it nds a method appropriate for a method call
Usage
onMethodSelection { expr, node ->
(node.declaringClass.name == 'java.lang.String') {
// calling a method on 'String'
// let’s perform additional checks!
(++count>2) {
addStaticTypeError("You can use only 2 calls on String in
your source code",expr)
}
}
}
The type checker works by inferring argument types of a method call, then chooses a target
method. If it nds one that corresponds, then it triggers this event. It is for example interesting
if you want to react on a speci c method call, such as entering the scope of a method that
takes a closure as argument (as in builders).Please note that this event may be thrown for
various types of expressions, not only method calls (binary expressions for example).
Called When Called by the type checker when it fails to nd an appropriate method for a method call
http://docs.groovy-lang.org/latest/html/documentation/ 151/502
1/6/2019 Groovy Language Documentation
Usage
methodNotFound { receiver, name, argList, argTypes, call ->
// receiver is the inferred type of the receiver
// name is the name of the called method
// argList is the list of arguments the method was called with
// argTypes is the array of inferred types for each argument
// call is the method call for which we couldn’t find a target
method
(receiver==classNodeFor( )
&& name=='longueur'
&& argList.size()==0) {
handled =
newMethod('longueur', classNodeFor( ))
}
}
Unlike onMethodSelection , this event is sent when the type checker cannot nd a target
method for a method call (instance or static). It gives you the chance to intercept the error
before it is sent to the user, but also set the target method.For this, you need to return a list of
MethodNode . In most situations, you would either return: an empty list, meaning that you
didn’t nd a corresponding method, a list with exactly one element, saying that there’s no
doubt about the target methodIf you return more than one MethodNode, then the compiler
would throw an error to the user stating that the method call is ambiguous, listing the
possible methods.For convenience, if you want to return only one method, you are allowed to
return it directly instead of wrapping it into a list.
Called When Called by the type checker before type checking a method body
Usage
beforeVisitMethod { methodNode ->
// tell the type checker we will handle the body by ourselves
handled = methodNode.name.startsWith('skip')
}
The type checker will call this method before starting to type check a method body. If you
want, for example, to perform type checking by yourself instead of letting the type checker do
it, you have to set the handled ag to true.This event can also be used to help de ning the
scope of your extension (for example, applying it only if you are inside method foo).
Called When Called by the type checker after type checking a method body
http://docs.groovy-lang.org/latest/html/documentation/ 152/502
1/6/2019 Groovy Language Documentation
Usage
afterVisitMethod { methodNode ->
scopeExit {
(methods>2) {
addStaticTypeError("Method ${methodNode.name} contains
more than 2 method calls", methodNode)
}
}
}
Gives you the opportunity to perform additional checks after a method body is visited by the
type checker. This is useful if you collect information, for example, and want to perform
additional checks once everything has been collected.
Called When Called by the type checker before type checking a class
Usage
beforeVisitClass { classNode ->
name = classNode.nameWithoutPackage
(!(name[0] 'A'..'Z')) {
addStaticTypeError("Class '${name}' doesn't start with an
uppercase letter",classNode)
}
}
If a class is type checked, then before visiting the class, this event will be sent. It is also the
case for inner classes de ned inside a class annotated with @TypeChecked . It can help you
de ne the scope of your extension, or you can even totally replace the visit of the type checker
with a custom type checking implementation. For that, you would have to set the handled
ag to true .
Called When Called by the type checker after having nished the visit of a type checked class
Usage
afterVisitClass { classNode ->
name = classNode.nameWithoutPackage
(!(name[0] 'A'..'Z')) {
addStaticTypeError("Class '${name}' doesn't start with an
uppercase letter",classNode)
}
}
Called for every class being type checked after the type checker nished its work. This includes
classes annotated with @TypeChecked and any inner/anonymous class de ned in the same
class with is not skipped.
http://docs.groovy-lang.org/latest/html/documentation/ 153/502
1/6/2019 Groovy Language Documentation
Called When Called when the type checker thinks that an assignment is incorrect, meaning that the right
hand side of an assignment is incompatible with the left hand side
Usage
incompatibleAssignment { lhsType, rhsType, expr ->
(isBinaryExpression(expr) && isAssignment(expr.operation.type))
{
(lhsType==classNodeFor( ) &&
rhsType==classNodeFor( )) {
handled =
}
}
}
Gives the developer the ability to handle incorrect assignments. This is for example useful if a
class overrides setProperty , because in that case it is possible that assigning a variable of
one type to a property of another type is handled through that runtime mechanism. In that
case, you can help the type checker just by telling it that the assignment is valid (using
handled set to true ).
Called When Called when the type checker cannot choose between several candidate methods
Usage
ambiguousMethods { methods, origin ->
// choose the method which has an Integer as parameter type
methods.find { it.parameters.any { it.type == classNodeFor( )
} }
}
Gives the developer the ability to handle incorrect assignments. This is for example useful if a
class overrides setProperty , because in that case it is possible that assigning a variable of
one type to a property of another type is handled through that runtime mechanism. In that
case, you can help the type checker just by telling it that the assignment is valid (using
handled set to true ).
Of course, an extension script may consist of several blocks, and you can have multiple blocks responding to the same event. This
makes the DSL look nicer and easier to write. However, reacting to events is far from su cient. If you know you can react to
events, you also need to deal with the errors, which implies several helper methods that will make things easier.
http://docs.groovy-lang.org/latest/html/documentation/ 154/502
1/6/2019 The extension script delegates to the org.codehaus.groovy.transform.stc.GroovyTypeCheckingExtensionSupport
Groovy Language Documentation
(http://docs.groovy-lang.org/2.5.5/html/gapi/index.html?
org/codehaus/groovy/transform/stc/GroovyTypeCheckingExtensionSupport.html) class, meaning that you have direct access to
the following variables:
generatedMethods: a list of "generated methods", which is in fact the list of "dummy" methods that you can create inside a
type checking extension using the newMethod calls
The type checking context contains a lot of information that is useful in context for the type checker. For example, the current
stack of enclosing method calls, binary expressions, closures, … This information is in particular important if you have to know
where you are when an error occurs and that you want to handle it.
Class nodes
Handling class nodes is something that needs particular attention when you work with a type checking extension. Compilation
works with an abstract syntax tree (AST) and the tree may not be complete when you are type checking a class. This also means
that when you refer to types, you must not use class literals such as String or HashSet , but to class nodes representing those
types. This requires a certain level of abstraction and understanding how Groovy deals with class nodes. To make things easier,
Groovy supplies several helper methods to deal with class nodes. For example, if you want to say "the type for String", you can
write:
classNodeFor( )
You would also note that there is a variant of classNodeFor that takes a String as an argument, instead of a Class . In general,
you should not use that one, because it would create a class node for which the name is String , but without any method, any
property, … de ned on it. The rst version returns a class node that is resolved but the second one returns one that is not. So the
latter should be reserved for very special cases.
The second problem that you might encounter is referencing a type which is not yet compiled. This may happen more often than
you think. For example, when you compile a set of les together. In that case, if you want to say "that variable is of type Foo" but
Foo is not yet compiled, you can still refer to the Foo class node using lookupClassNodeFor :
lookupClassNodeFor('Foo')
Likewise, getting the type of an AST node is just a matter of calling getType on that node. This would in general be what you
want, but there’s something that you must understand:
getType returns the inferred type of an expression. This means that it will not return, for a variable declared of type Object
the class node for Object , but the inferred type of this variable at this point of the code ( ow typing)
if you want to access the origin type of a variable (or eld/parameter), then you must call the appropriate method on the AST
node
Throwing an error
To throw a type checking error, you only have to call the addStaticTypeError method which takes two arguments:
an AST node responsible for the error. It’s better to provide the best suiting AST node because it will be used to retrieve the line
and column numbers
isXXXExpression
http://docs.groovy-lang.org/latest/html/documentation/ 155/502
1/6/2019 It is often required to know the type of an AST node. For readability, the DSLDocumentation
Groovy Language provides a special isXXXExpression method that will
delegate to x instance of XXXExpression . For example, instead of writing:
(node ) {
...
}
which requires you to import the BinaryExpression class, you can just write:
(isBinaryExpression(node)) {
...
}
Virtual methods
When you perform type checking of dynamic code, you may often face the case when you know that a method call is valid but
there is no "real" method behind it. As an example, take the Grails dynamic nders. You can have a method call consisting of a
method named ndByName(…). As there’s no ndByName method de ned in the bean, the type checker would complain. Yet, you
would know that this method wouldn’t fail at runtime, and you can even tell what is the return type of this method. For this case,
the DSL supports two special constructs that consist of phantom methods. This means that you will return a method node that
doesn’t really exist but is de ned in the context of type checking. Three methods exist:
All three variants do the same: they create a new method node which name is the supplied name and de ne the return type of
this method. Moreover, the type checker would add those methods in the generatedMethods list (see isGenerated below). The
reason why we only set a name and a return type is that it is only what you need in 90% of the cases. For example, in
the findByName example upper, the only thing you need to know is that findByName wouldn’t fail at runtime, and that it returns
a domain class. The Callable version of return type is interesting because it defers the computation of the return type when the
type checker actually needs it. This is interesting because in some circumstances, you may not know the actual return type when
the type checker demands it, so you can use a closure that will be called each time getReturnType is called by the type checker
on this method node. If you combine this with deferred checks, you can achieve pretty complex type checking including handling
of forward references.
newMethod(name) {
// each time getReturnType on this method node will be called, this closure will be called!
println 'Type checker called me!'
lookupClassNodeFor( ) // return type
}
Should you need more than the name and return type, you can always create a new MethodNode by yourself.
Scoping
Scoping is very important in DSL type checking and is one of the reasons why we couldn’t use a pointcut based approach to DSL
type checking. Basically, you must be able to de ne very precisely when your extension applies and when it does not. Moreover,
you must be able to handle situations that a regular type checker would not be able to handle, such as forward references:
point a(1,1)
line a,b // b is referenced afterwards!
point b(5,2)
builder.foo {
bar
baz(bar)
}
http://docs.groovy-lang.org/latest/html/documentation/ 156/502
1/6/2019 Your extension, then, should only be active once you’ve entered
Groovythe foo method,
Language and inactive outside of this scope. But you
Documentation
could have complex situations like multiple builders in the same le or embedded builders (builders in builders). While you should
not try to x all this from start (you must accept limitations to type checking), the type checker does o er a nice mechanism to
handle this: a scoping stack, using the newScope and scopeExit methods.
a parent scope
scope = newScope()
scope.secondPassChecks = []
//...
scope.secondPassChecks << { println 'executed later' }
// ...
scopeExit {
secondPassChecks*.run() // execute deferred checks
}
That is to say, that if at some point you are not able to determine the type of an expression, or that you are not able to check at
this point that an assignment is valid or not, you can still make the check later… This is a very powerful feature. Now, newScope
and scopeExit provide some interesting syntactic sugar:
newScope {
secondPassChecks = []
}
At anytime in the DSL, you can access the current scope using getCurrentScope() or more simply currentScope :
//...
currentScope.secondPassChecks << { println 'executed later' }
// ...
determine a pointcut where you push a new scope on stack and initialize custom variables within this scope
using the various events, you can use the information stored in your custom scope to perform checks, defer checks,…
determine a pointcut where you exit the scope, call scopeExit and eventually perform additional checks
isDynamic : takes a VariableExpression as argument and returns true if the variable is a DynamicExpression, which means, in
a script, that it wasn’t de ned using a type or def .
isGenerated : takes a MethodNode as an argument and tells if the method is one that was generated by the type checker
extension using the newMethod method
http://docs.groovy-lang.org/latest/html/documentation/ 157/502
1/6/2019 isAnnotatedBy : takes an AST node and a Class (or ClassNode), and tellsDocumentation
Groovy Language if the node is annotated with this class. For example:
isAnnotatedBy(node, NotNull)
getTargetMethod : takes a method call as argument and returns the MethodNode that the type checker has determined for it
delegatesTo : emulates the behaviour of the @DelegatesTo annotation. It allows you to tell that the argument will delegate
to a speci c type (you can also specify the delegation strategy)
a Groovy source le, corresponding to the type checking extension, is available on compilation classpath
this le is compiled by the Groovy compiler for each source unit being compiled (often, a source unit corresponds to a single
le)
It is a very convenient way to develop type checking extensions, however it implies a slower compilation phase, because of the
compilation of the extension itself for each le being compiled. For those reasons, it can be practical to rely on a precompiled
extension. You have two options to do this:
write the extension in Groovy, compile it, then use a reference to the extension class instead of the source
write the extension in Java, compile it, then use a reference to the extension class
Writing a type checking extension in Groovy is the easiest path. Basically, the idea is that the type checking extension script
becomes the body of the main method of a type checking extension class, as illustrated here:
org.codehaus.groovy.transform.stc.
. { 1
@Override
run() { 2
unresolvedVariable { ->
('robot'== .name) {
storeType( , classNodeFor( )) 3
handled =
}
}
}
}
config.addCompilationCustomizers(
(
,
extensions:['typing.PrecompiledExtension'])
)
The di erence is that instead of using a path in classpath, you just specify the fully quali ed class name of the precompiled
extension.
In case you really want to write an extension in Java, then you will not bene t from the type checking extension DSL. The extension
above can be rewritten in Java this way:
http://docs.groovy-lang.org/latest/html/documentation/ 158/502
1/6/2019 Groovy Language Documentation
org.codehaus.groovy.ast. ;
org.codehaus.groovy.ast.expr. ;
org.codehaus.groovy.transform.stc. ;
org.codehaus.groovy.transform.stc. ;
{ 1
( typeCheckingVisitor) {
(typeCheckingVisitor);
}
@Override
handleUnresolvedVariableExpression( vexp) { 2
("robot".equals(vexp.getName())) {
storeType(vexp, .make( . ));
setHandled( );
;
}
;
}
a type checking extension used with @CompileStatic will in general not be su cient to let the compiler know how to
generate statically compilable code from "unsafe" code
it is possible to use a type checking extension with @CompileStatic just to enhance type checking, that is to say introduce
more compilation errors, without actually dealing with dynamic code
Let’s explain the rst point, which is that even if you use an extension, the compiler will not know how to compile your code
statically: technically, even if you tell the type checker what is the type of a dynamic variable, for example, it would not know how
to compile it. Is it getBinding('foo') , getProperty('foo') , delegate.getFoo() ,…? There’s absolutely no direct way to tell
the static compiler how to compile such code even if you use a type checking extension (that would, again, only give hints about
the type).
One possible solution for this particular example is to instruct the compiler to use mixed mode compilation. The more advanced
one is to use AST transformations during type checking but it is far more complex.
Type checking extensions allow you to help the type checker where it fails, but it also allow you to fail where it doesn’t. In that
context, it makes sense to support extensions for @CompileStatic too. Imagine an extension that is capable of type checking
SQL queries. In that case, the extension would be valid in both dynamic and static context, because without the extension, the
code would still pass.
http://docs.groovy-lang.org/latest/html/documentation/ 159/502
1/6/2019 Mixed mode compilation Groovy Language Documentation
In the previous section, we highlighted the fact that you can activate type checking extensions with @CompileStatic . In that
context, the type checker would not complain anymore about some unresolved variables or unknown method calls, but it would
still wouldn’t know how to compile them statically.
Mixed mode compilation o ers a third way, which is to instruct the compiler that whenever an unresolved variable or method call
is found, then it should fall back to a dynamic mode. This is possible thanks to type checking extensions and a special
makeDynamic call.
robot.move 100
And let’s try to activate our type checking extension using @CompileStatic instead of @TypeChecked :
config = ()
config.addCompilationCustomizers(
(
, 1
extensions:['robotextension.groovy']) 2
)
shell = (config)
robot = ()
shell.setVariable('robot', robot)
shell.evaluate(script)
The script will run ne because the static compiler is told about the type of the robot variable, so it is capable of making a direct
call to move . But before that, how did the compiler know how to get the robot variable? In fact by default, in a type checking
extension, setting handled=true on an unresolved variable will automatically trigger a dynamic resolution, so in this case you
don’t have anything special to make the compiler use a mixed mode. However, let’s slightly update our example, starting from the
robot script:
move 100
Here you can notice that there is no reference to robot anymore. Our extension will not help then because we will not be able to
instruct the compiler that move is done on a Robot instance. This example of code can be executed in a totally dynamic way
thanks to the help of a groovy.util.DelegatingScript (http://docs.groovy-lang.org/2.5.5/html/gapi/index.html?
groovy/util/DelegatingScript.html):
config = ()
config.scriptBaseClass = 'groovy.util.DelegatingScript' 1
shell = (config)
runner = shell.parse(script) 2
runner.setDelegate( ()) 3
runner.run() 4
If we want this to pass with @CompileStatic , we have to use a type checking extension, so let’s update our con guration:
http://docs.groovy-lang.org/latest/html/documentation/ 160/502
1/6/2019 Groovy Language Documentation
config.addCompilationCustomizers(
(
, 1
extensions:['robotextension2.groovy']) 2
Then in the previous section we have learnt how to deal with unrecognized method calls, so we are able to write this extension:
robotextension2.groovy
&& call.implicitThis 2
&& 'move'==name 3
&& argTypes.length==1 4
) {
handled = 6
newMethod('move', classNodeFor( )) 7
}
}
If you try to execute this code, then you could be surprised that it actually fails at runtime:
java.lang.NoSuchMethodError: java.lang.Object.move()Ltyping/Robot;
The reason is very simple: while the type checking extension is su cient for @TypeChecked , which does not involve static
compilation, it is not enough for @CompileStatic which requires additional information. In this case, you told the compiler that
the method existed, but you didn’t explain to it what method it is in reality, and what is the receiver of the message (the delegate).
Fixing this is very easy and just implies replacing the newMethod call with something else:
robotextension3.groovy
}
}
So when the compiler will have to generate bytecode for the call to move , since it is now marked as a dynamic call, it will fallback
to the dynamic compiler and let it handle the call. And since the extension tells us that the return type of the dynamic call is a
Robot , subsequent calls will be done statically!
Some would wonder why the static compiler doesn’t do this by default without an extension. It is a design decision:
if the code is statically compiled, we normally want type safety and best performance
so if unrecognized variables/method calls are made dynamic, you loose type safety, but also all support for typos at compile
time!
In short, if you want to have mixed mode compilation, it has to be explicit, through a type checking extension, so that the
compiler, and the designer of the DSL, are totally aware of what they are doing.
a variable ( VariableExpression )
If that is not enough, then it means that static compilation cannot be done directly and that you have to rely on AST
transformations.
First of all, you would explicitly break the contract of type checking, which is to annotate, and only annotate the AST. Type
checking should not modify the AST tree because you wouldn’t be able to guarantee anymore that code without
the @TypeChecked annotation behaves the same without the annotation.
If your extension is meant to work with @CompileStatic, then you can modify the AST because this is indeed
what @CompileStatic will eventually do. Static compilation doesn’t guarantee the same semantics at dynamic Groovy so there
is e ectively a di erence between code compiled with @CompileStatic and code compiled with @TypeChecked. It’s up to you to
choose whatever strategy you want to update the AST, but probably using an AST transformation that runs before type
checking is easier.
if you cannot rely on a transformation that kicks in before the type checker, then you must be very careful
The type checking phase is the last phase running in the compiler before bytecode generation. All other AST
transformations run before that and the compiler does a very good job at " xing" incorrect AST generated before
the type checking phase. As soon as you perform a transformation during type checking, for example directly in a
type checking extension, then you have to do all this work of generating a 100% compiler compliant abstract
syntax tree by yourself, which can easily become complex. That’s why we do not recommend to go that way if you
are beginning with type checking extensions and AST transformations.
Examples
Examples of real life type checking extensions are easy to nd. You can download the source code for Groovy and take a look at
the TypeCheckingExtensionsTest
(https://github.com/apache/groovy/blob/master/src/test/groovy/transform/stc/TypeCheckingExtensionsTest.groovy) class which is
linked to various extension scripts (https://github.com/apache/groovy/tree/master/src/test-resources/groovy/transform/stc).
An example of a complex type checking extension can be found in the Markup Template Engine (markup-template-engine.html)
source code: this template engine relies on a type checking extension and AST transformations to transform templates into fully
statically compiled code. Sources for this can be found here (https://github.com/apache/groovy/tree/master/subprojects/groovy-
templates/src/main/groovy/groovy/text/markup).
http://docs.groovy-lang.org/latest/html/documentation/ 162/502
1/6/2019 2. Tools Groovy Language Documentation
The easiest way to run a Groovy script, test or application is to run the following command at your shell prompt:
The .groovy part is optional. The groovy command supports a number of command line switches:
-cp <path> -classpath <path> Specify the compilation groovy -cp lib/dep.jar
--classpath <path> classpath. Must be the rst MyScript
argument.
http://docs.groovy-lang.org/latest/html/documentation/ 163/502
1/6/2019 Groovy Language Documentation
Short version Long version Description Example
groovyc MyClass.groovy
This will produce a MyClass.class le (as well as other .class les depending on the contents of the source). groovyc supports
a number of command line switches:
http://docs.groovy-lang.org/latest/html/documentation/ 164/502
1/6/2019 Groovy Language Documentation
Short version Long version Description Example
Notes: * for a full description of joint compilation, see the joint compilation section.
<groovyc>
Description
Compiles Groovy source les and, if joint compilation option is used, Java source les.
Required taskdef
Assuming all the groovy jars you need are in my.classpath (this will be groovy-VERSION.jar , groovy-ant-VERSION.jar plus
any modules and transitive dependencies you might be using) you will need to declare this task at some point in the build.xml
prior to the groovyc task being invoked.
name="groovyc"
classname="org.codehaus.groovy.ant.Groovyc"
classpathref="my.classpath"
<groovyc> Attributes
http://docs.groovy-lang.org/latest/html/documentation/ 165/502
1/6/2019 Groovy Language Documentation
Attribute Description Required
http://docs.groovy-lang.org/latest/html/documentation/ 166/502
1/6/2019 Groovy Language Documentation
Attribute Description Required
http://docs.groovy-lang.org/latest/html/documentation/ 167/502
1/6/2019 Groovy Language Documentation
Attribute Description Required
Example:
srcdir="src" destdir="target/classes"
Notes:
The nested javac task behaves more or less as documented for the top-level javac task. srcdir , destdir , classpath ,
encoding for the nested javac task are taken from the enclosing groovyc task. If these attributes are speci ed then they
are added, they do not replace. In fact, you should not attempt to overwrite the destination. Other attributes and nested
elements are una ected, for example fork , memoryMaximumSize , etc. may be used freely.
Joint Compilation
Joint compilation is enabled by using an embedded javac element, as shown in the following example:
srcdir="${testSourceDirectory}" destdir="${testClassesDirectory}"
path="${mainClassesDirectory}"
path="${testClassesDirectory}"
refid="testPath"
It is rare to specify srcdir and destdir , the nested javac task is provided with the srcdir and destdir values from the
enclosing groovyc task, and it is invariable the right thing to do just to leave this as is. To restate: the javac task gets the
srcdir , destdir and classpath from the enclosing groovyc task.
More details about joint compilation can be found in the joint compilation section.
2.2.3. Gant
Gant (https://github.com/Gant/Gant) is a tool for scripting Ant tasks using Groovy instead of XML to specify the logic. As such, it
has exactly the same features as the Groovyc Ant task.
2.2.4. Gradle
http://docs.groovy-lang.org/latest/html/documentation/ 168/502
1/6/2019 Gradle (http://www.gradle.org/) is a build tool that allows Groovy
you to leverage
Languagethe exibility of Ant (http://ant.apache.org/), while
Documentation
keeping the simplicity of convention over con guration that tools like Maven (http://maven.apache.org/) o er. Builds are speci ed
using a Groovy DSL, which o ers great exibility and succinctness.
A third approach is to use Maven’s Ant plugin to compile a groovy project. Note that the Ant plugin is bound to the compile and
test-compile phases of the build in the example below. It will be invoked during these phases and the contained tasks will be
carried out which runs the Groovy compiler over the source and test directories. The resulting Java classes will coexist with and be
treated like any standard Java classes compiled from Java source and will appear no di erent to the JRE, or the JUnit runtime.
http://docs.groovy-lang.org/latest/html/documentation/ 169/502
1/6/2019 Groovy Language Documentation
xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-
instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-
v4_0_0.xsd"
4.0.0
com.mycomp.MyGroovy
MyGroovy
jar
1.0-SNAPSHOT
Maven Example building a Groovy project
junit
junit
3.8.1
test
org.codehaus.groovy
groovy-all
2.5.0
pom <!-- required JUST since Groovy 2.5.0 -->
maven-antrun-plugin
compile
compile
dir="${basedir}/src/main/groovy"
name="groovyc"
classname="org.codehaus.groovy.ant.Groovyc"
refid="maven.compile.classpath"
dir="${project.build.outputDirectory}"
destdir="${project.build.outputDirectory}"
srcdir="${basedir}/src/main/groovy/" listfiles="true"
refid="maven.compile.classpath"
run
test-compile
test-compile
dir="${basedir}/src/test/groovy"
name="groovyc"
classname="org.codehaus.groovy.ant.Groovyc"
refid="maven.test.classpath"
dir="${project.build.testOutputDirectory}"
destdir="${project.build.testOutputDirectory}"
srcdir="${basedir}/src/test/groovy/" listfiles="true"
refid="maven.test.classpath"
http://docs.groovy-lang.org/latest/html/documentation/ 170/502
1/6/2019 Groovy Language Documentation
run
This assumes you have a Maven project setup with groovy subfolders as peers to the java src and test subfolders. You can use
the java / jar archetype to set this up then rename the java folders to groovy or keep the java folders and just create groovy
peer folders. There exists, also a groovy plugin which has not been tested or used in production. After de ning the build section as
in the above example, you can invoke the typical Maven build phases normally. For example, mvn test will execute the test
phase, compiling Groovy source and Groovy test source and nally executing the unit tests. If you run mvn jar it will execute the
jar phase bundling up all of your compiled production classes into a jar after all of the unit tests pass. For more detail on Maven
build phases consult the Maven2 documentation.
GMaven
GMaven (https://github.com/groovy/gmaven) is the original Maven plugin for Groovy, supporting both compiling and scripting
Groovy.
Important:
You should be aware that GMaven is not supported anymore and can have di culties with joint compilation. GMavenPlus can be
a good replacement, but if you are having problems with joint compilation, you might consider the Groovy Eclipse maven plugin.
GMavenPlus
GMavenPlus (https://github.com/groovy/GMavenPlus) is a rewrite of GMaven and is in active development. It supports most of the
features of GMaven (a couple notable exceptions being mojo Javadoc tags (http://maven.apache.org/plugin-tools/maven-plugin-
tools-java/index.html) and support for older Groovy versions). Its joint compilation uses stubs (which means it has the same
potential issues as GMaven and Gradle). The main advantages over its predecessor are that it supports recent Groovy versions,
InvokeDynamic, Groovy on Android, GroovyDoc, and con guration scripts.
GMaven 2
Unlike the name might seem to suggest, GMaven 2 (http://groovy.github.io/gmaven/) is not aimed at replacing GMaven. In fact, it
removes the non-scripting features of the GMaven plugin. It has not yet had any release and appears to be inactive currently.
Joint compilation can be enabled using the -j ag with the command-line compiler, or using using a nested tag and all the
attributes and further nested tags as required for the Ant task.
It is important to know that if you don’t enable joint compilation and try to compile Java source les with the Groovy compiler, the
Java source les will be compiled as if they were Groovy sources. In some situations, this might work since most of the Java syntax
is compatible with Groovy, but semantics would be di erent.
buildscript {
repositories {
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:2.1.2'
classpath 'org.codehaus.groovy:groovy-android-gradle-plugin:1.0.0'
}
}
Then you will need to add a dependency on the grooid version of the Groovy compiler:
dependencies {
compile 'org.codehaus.groovy:groovy:2.4.7:grooid'
}
Note that if a Groovy jar does not provide a grooid classi er alternative, then it means that the jar is directly compatible with
Android. In that case, you can add the dependency directly like this:
dependencies {
compile 'org.codehaus.groovy:groovy:2.4.7:grooid' // requires the grooid classifier
compile ('org.codehaus.groovy:groovy-json:2.4.7') { // no grooid version available
transitive = // so do not depend on non-grooid
version
}
}
Note that the transitive=false parameter for groovy-json will let Gradle download the JSON support jar without adding a
dependency onto the normal jar of Groovy.
Features
No need for go command to execute bu er.
Rich cross-platform edit-line editing, history and completion thanks to JLine2 (https://github.com/jline/jline2).
Simple, yet robust, command system with online help, user alias support and more.
http://docs.groovy-lang.org/latest/html/documentation/ 172/502
1/6/2019 Groovy Language Documentation
./bin/groovysh --help
Evaluating Expressions
Simple Expressions
println "Hello"
Evaluation Result
When a complete expression is found, it is compiled and evaluated. The result of the evaluation is stored into the _ variable.
Multi-line Expressions
Multi-line/complex expressions (like closure or class de nitions) may be de ned over several lines. When the shell detects that it
has a complete expression it will compile and evaluate it.
De ne a Class
{
bar() {
println "baz"
}
}
foo = ()
foo.bar()
Variables
Shell variables are all untyped (i.e. no def or other type information).
foo = "bar"
But, this will evaluate a local variable and will not be saved to the shell’s environment:
foo = "bar"
Functions
Functions can be de ned in the shell, and will be saved for later use.
http://docs.groovy-lang.org/latest/html/documentation/ 173/502
1/6/2019 De ning a function is easy: Groovy Language Documentation
groovy:000> hello(name) {
groovy:001> println("Hello $name")
groovy:002> }
hello("Jason")
Internally the shell creates a closure to encapsulate the function and then binds the closure to a variable. So variables and
functions share the same namespace.
Commands
The shell has a number of di erent commands, which provide rich access to the shell’s environment.
Commands all have a name and a shortcut (which is something like \h ). Commands may also have some prede ned system
aliases. Users may also create their own aliases.
Recognized Commands
help
Display the list of commands (and aliases) or the help text for speci c command.
groovy:000> :help
Available commands:
:help (:h ) Display this help message
? (:? ) Alias to: :help
:exit (:x ) Exit the shell
:quit (:q ) Alias to: :exit
import (:i ) Import a class into the namespace
:display (:d ) Display the current buffer
:clear (:c ) Clear the buffer and reset the prompt counter
:show (:S ) Show variables, classes or imports
:inspect (:n ) Inspect a variable or the last result with the GUI object browser
:purge (:p ) Purge variables, classes, imports or preferences
:edit (:e ) Edit the current buffer
:load (:l ) Load a file or URL into the buffer
. (:. ) Alias to: :load
:save (:s ) Save the current buffer to a file
:record (:r ) Record the current session to a file
:history (:H ) Display, manage and recall edit-line history
:alias (:a ) Create an alias
:set (:= ) Set (or list) preferences
:grab (:g ) Add a dependency to the shell environment
:register (:rc) Register a new command with the shell
:doc (:D ) Open a browser window displaying the doc for the argument
While in the interactive shell, you can ask for help for any command to get more details about its syntax or function. Here is an
example of what happens when you ask for help for the help command:
http://docs.groovy-lang.org/latest/html/documentation/ 174/502
1/6/2019 Groovy Language Documentation
groovy:000> :help :help
exit
Exit the shell.
This is the only way to exit the shell. Well, you can still CTRL-C , but the shell will complain about an abnormal shutdown of the
JVM.
import
Add a custom import which will be included for all shell evaluations.
grab
Grab a dependency (Maven, Ivy, etc.) from Internet sources or cache, and add it to the Groovy Shell environment.
display
Display the contents of the current bu er.
This only displays the bu er of an incomplete expression. Once the expression is complete, the bu er is rest. The prompt will
update to show the size of the current bu er as well.
Example
clear
Clears the current bu er, resetting the prompt counter to 000. Can be used to recover from compilation errors.
show
Show variables, classes or preferences or imports.
show variables
show classes
show imports
show preferences
show all
inspect
Opens the GUI object browser to inspect a variable or the result of the last evaluation.
http://docs.groovy-lang.org/latest/html/documentation/ 175/502
1/6/2019 purge Groovy Language Documentation
Purges objects from the shell.
purge variables
purge classes
purge imports
purge preferences
purge all
edit
Edit the current bu er in an external editor.
Currently only works on UNIX systems which have the EDITOR environment variable set, or have con gured the editor
preference.
load
Load one or more les (or urls) into the bu er.
save
Saves the bu er’s contents to a le.
record
Record the current session to a le.
record start
record stop
record status
history
Display, manage and recall edit-line history.
history show
history recall
history flush
history clear
alias
Create an alias.
doc
Opens a browser with documentation for the provided class. For example:
set
Set or list preferences.
Preferences
Some of aspects of groovysh behaviors can be customized by setting preferences. Preferences are set using the set command
or the := shortcut.
http://docs.groovy-lang.org/latest/html/documentation/ 176/502
1/6/2019 Recognized Preferences Groovy Language Documentation
interpreterMode
Allows the use of typed variables (i.e. def or other type information):
groovy:000> def x = 3
===> 3
groovy:000> x
===> 3
It’s especially useful for copy&pasting code from tutorials etc. into the running session.
verbosity
Set the shell’s verbosity level. Expected to be one of:
DEBUG
VERBOSE
INFO
QUIET
Default is INFO .
If this preference is set to an invalid value, then the previous setting will be used, or if there is none, then the preference is
removed and the default is used.
colors
Set the shell’s use of colors.
Default is true .
show-last-result
Show the last result after an execution.
Default is true .
sanitize-stack-trace
Sanitize (trim-down/ lter) stack traces.
Default is true .
editor
Con gures the editor used by the edit command.
Mac OS XTo use TextEdit, the default text editor on Mac OS X, con gure: set editor
/Applications/TextEdit.app/Contents/MacOS/TextEdit
Setting a Preference
Listing Preferences
To list the current set preferences (and their values):
Limitation: At the moment, there is no way to list all of the known/available preferences to be set.
Pro le Scripts
http://docs.groovy-lang.org/latest/html/documentation/ 177/502
1/6/2019 $HOME/.groovy/groovysh.profile Groovy Language Documentation
This script, if it exists, is loaded when the shell starts up.
$HOME/.groovy/groovysh.rc
This script, if it exists, is loaded when the shell enters interactive mode.
State
$HOME/.groovy/groovysh.history
Edit-line history is stored in this le.
Custom commands
The register command allows you to register custom commands in the shell. For example, writing the following will register the
Stats command:
where the Stats class is a class extending the org.codehaus.groovy.tools.shell.CommandSupport class. For example:
org.codehaus.groovy.tools.shell.
org.codehaus.groovy.tools.shell.
{
( shell) {
(shell, 'stats', 'T')
}
execute( args) {
println "Free memory: ${Runtime.runtime.freeMemory()}"
}
groovy:000> :stats
stats
Free memory: 139474880
groovy:000>
Note that the command class must be found on classpath: you cannot de ne a new command from within the shell.
Troubleshooting
Please report (https://issues.apache.org/jira/browse/GROOVY) any problems you run into. Please be sure to mark the JIRA issue
with the Groovysh component.
Platform Problems
Problems loading the JLine DLL
On Windows, JLine2 (https://github.com/jline/jline2) (which is used for the fancy shell input/history/completion u ), uses a tiny
DLL le to trick the evil Windows faux-shell ( CMD.EXE or COMMAND.COM ) into providing Java with unbu ered input. In some rare
cases, this might fail to load or initialize.
One solution is to disable the frills and use the unsupported terminal instance. You can do that on the command-line using the
--terminal ag and set it to one of:
none
false
off
jline.UnsupportedTerminal
groovysh --terminal=none
http://docs.groovy-lang.org/latest/html/documentation/
Problems with Cygwin on Windows 178/502
1/6/2019 Some people have issues when running groovysh with cygwin.
GroovyIf you have troubles,
Language the following may help:
Documentation
2.4.2. Basics
4. When you select Run from the Actions menu, the console compiles the script and runs it.
5. Anything that would normally be printed on System.out is printed in the output area.
2.4.3. Features
http://docs.groovy-lang.org/latest/html/documentation/ 179/502
1/6/2019 Groovy Language Documentation
./bin/groovyConsole --help
: groovyConsole [options] [filename]
allows a user to enter run scripts.
--configscript=PARAM A script tweaking the compiler configuration options
-cp, -classpath, --classpath
to find the files - must be first
argument
-D, --define=<name=value> a system
-h, --help help message
-i, --indy ( ) compilation scripts
-pa, --parameters metadata reflection on method parameter
names (jdk8+ only)
-V, --version the version
Running Scripts
There are several shortcuts that you can use to run scripts or code snippets:
Ctrl+Enter and Ctrl+R are both shortcut keys for Run Script .
If you highlight just part of the text in the input area, then Groovy runs just that text.
The result of a script is the the value of the last expression executed.
You can turn the System.out capture on and o by selecting Capture System.out from the Actions menu
Editing Files
You can open any text le, edit it, run it (as a Groovy Script) and then save it again when you are nished.
Select File > New File (shortcut key ctrl+Q ) to start again with a blank input area
The console remembers the last ten script runs. You can scroll back and forth through the history by selecting Next and
Previous from the Edit menu. Ctrl-N and ctrl-P are convenient shortcut keys.
The last result (null and non-null) for every run in the history is bound into a list variable named (two underscores). The result
of the last run is [-1] , the result of the second to last run is __[-2] and so forth.
Interrupting a script
The Groovy console is a very handy tool to develop scripts. Often, you will nd yourself running a script multiple times until it
works the way you want it to. However, what if your code takes too long to nish or worse, creates an in nite loop? Interrupting
script execution can be achieved by clicking the interrupt button on the small dialog box that pops up when a script is
executing or through the interrupt icon in the tool bar.
However, this may not be su cient to interrupt a script: clicking the button will interrupt the execution thread, but if your code
doesn’t handle the interrupt ag, the script is likely to keep running without you being able to e ectively stop it. To avoid that, you
have to make sure that the Script > Allow interruption menu item is agged. This will automatically apply an AST
transformation to your script which will take care of checking the interrupt ag ( @ThreadInterrupt ). This way, you guarantee
that the script can be interrupted even if you don’t explicitly handle interruption, at the cost of extra execution time.
And more
You can change the font size by selecting Smaller Font or Larger Font from the Actions menu
You can drag’n’drop a Groovy script over the text area to open a le
http://docs.groovy-lang.org/latest/html/documentation/ 180/502
1/6/2019 You can modify the classpath with which the script in the console
Groovy is being
Language run by adding a new JAR or a directory to the
Documentation
classpath from the Script menu
Error hyperlinking from the output area when a compilation error is expected or when an exception is thrown
You can enable InvokeDynamic (Indy) compilation mode by selecting Enable Indy Compilation from the Script menu
groovy.ui. ;
...
console = ();
console.setVariable("var1", getValueOfVar1());
console.setVariable("var2", getValueOfVar2());
console.run();
...
Once the console is launched, you can use the variable values in Groovy code.
What you see here is the usual textual representation of a Map. But, what if we enabled custom visualization of certain results?
The Swing console allows you to do just that. First of all, you have to ensure that the visualization option is ticked:
View → Visualize Script Results — for the record, all settings of the Groovy Console are stored and remembered thanks to
the Preference API. There are a few result visualizations built-in: if the script returns a java.awt.Image , a javax.swing.Icon , or
a java.awt.Component with no parent, the object is displayed instead of its toString() representation. Otherwise, everything
else is still just represented as text. Now, create the following Groovy script in ~/.groovy/OutputTransforms.groovy :
javax.swing.*
The Groovy Swing console will execute that script on startup, injecting a transforms list in the binding of the script, so that you can
add your own script results representations. In our case, we transform the Map into a nice-looking Swing JTable. And we’re now
able to visualize maps in a friendly and attractive fashion, as the screenshot below shows:
http://docs.groovy-lang.org/latest/html/documentation/ 181/502
1/6/2019 Groovy Language Documentation
-classpath, -cp --classpath Specify where to nd the class les - must be rst argument
-exclude <pkglist> Specify a list of packages to exclude (separated by colons for all
operating systems)
-nomainforscripts Don’t include the implicit 'public static void main' method for scripts
-sourcepath <pathlist> Specify where to nd source les (dirs separated by platform path
separator)
Required taskdef
Assuming all the groovy jars you need are in my.classpath (this will be groovy-VERSION.jar , groovy-ant-VERSION.jar ,
groovy-groovydoc-VERSION.jar plus any modules and transitive dependencies you might be using) you will need to declare
this task at some point in the build.xml prior to the groovydoc task being invoked.
http://docs.groovy-lang.org/latest/html/documentation/ 183/502
1/6/2019 Groovy Language Documentation
name = "groovydoc"
classname = "org.codehaus.groovy.ant.Groovydoc"
classpathref = "my.classpath"
<groovydoc> Attributes
doctitle Include title for the package index( rst) page (html-code). No
private Show all classes and members (i.e. including private ones) if No
set to ``true''.
link
Create link to groovydoc/javadoc output at the given URL.
http://docs.groovy-lang.org/latest/html/documentation/ 184/502
1/6/2019 Groovy Language Documentation
name = "groovydoc"
classname = "org.codehaus.groovy.ant.Groovydoc"
classpathref = "path_to_groovy_all"
destdir = "${docsDirectory}/gapi"
sourcepath = "${mainSourceDirectory}"
packagenames = "**.*"
use = "true"
windowtitle = "${title}"
doctitle = "${title}"
header = "${title}"
footer = "${docFooter}"
overview = "src/main/overview.html"
private = "false"
packages="java.,org.xml.,javax.,org.xml."
href="http://docs.oracle.com/javase/8/docs/api/"
packages="org.apache.tools.ant." href="http://docs.groovy-
lang.org/docs/ant/api/"
packages="org.junit.,junit.framework."
href="http://junit.org/junit4/javadoc/latest/"
packages="groovy.,org.codehaus.groovy." href="http://docs.groovy-
lang.org/latest/html/api/"
packages="org.codehaus.gmaven."
href="http://groovy.github.io/gmaven/apidocs/"
ant = ()
ant.taskdef(name: "groovydoc", classname: "org.codehaus.groovy.ant.Groovydoc")
ant.groovydoc(
destdir : "${docsDirectory}/gapi",
sourcepath : "${mainSourceDirectory}",
packagenames : "**.*",
: "true",
windowtitle : "${title}",
doctitle : "${title}",
header : "${title}",
footer : "${docFooter}",
overview : "src/main/overview.html",
: "false") {
link(packages:"java.,org.xml.,javax.,org.xml.",href:"http://docs.oracle.com/javase/8/docs/api/")
link(packages:"groovy.,org.codehaus.groovy.", href:"http://docs.groovy-
lang.org/latest/html/api/")
link(packages:"org.apache.tools.ant.", href:"http://docs.groovy-
lang.org/docs/ant/api/")
link(packages:"org.junit.,junit.framework.",
href:"http://junit.org/junit4/javadoc/latest/")
link(packages:"org.codehaus.gmaven.",
href:"http://groovy.github.io/gmaven/apidocs/")
}
Custom templates
The groovydoc Ant task supports custom templates, but it requires two steps:
http://docs.groovy-lang.org/latest/html/documentation/ 185/502
1/6/2019 Groovy Language Documentation
org.codehaus.groovy.tools.groovydoc;
org.codehaus.groovy.ant. ;
/**
* Overrides GroovyDoc's default class template - for testing purpose only.
*
* @author Andre Steingress
*/
{
@Override
[] getClassTemplates() {
[]{"org/codehaus/groovy/tools/groovydoc/testfiles/classDocName.html"};
}
}
name = "groovydoc"
classname = "org.codehaus.groovy.ant.CustomGroovyDoc"
classpathref = "path_to_groovy_all"
Please note that template customization is provided as is. APIs are subject to change, so you must consider this as a fragile
feature.
TextMate Yes No No
(https://github.com/textmate/groovy.tmbundle)
SlickEdit Yes No No
(https://www.slickedit.com/products/slickedit/419-
the-most-powerful-groovy-editor-in-the-world/)
EditRocket Yes No No
(https://editrocket.com/features/groovy_editor.html)
3. User Guides
3.1. Getting started
3.1.1. Download
In this download area, you will be able to download the distribution (binary and source), the Windows installer and the
documentation for Groovy.
For a quick and e ortless start on Mac OSX, Linux or Cygwin, you can use SDKMAN! (http://sdkman.io/) (The Software
Development Kit Manager) to download and con gure any Groovy version of your choice. Basic instructions can be found below.
Stable
Download zip: Binary Release (https://bintray.com/artifact/download/groovy/maven/apache-groovy-binary-2.5.5.zip) | Source
Release (https://bintray.com/artifact/download/groovy/maven/groovy-src-2.5.5.zip)
You can learn more about this version in the release notes (http://groovy-lang.org/releasenotes/groovy-2.5.html) or in the
changelog (http://groovy-lang.org/changelogs/changelog-2.5.5.html).
Snapshots
For those who want to test the very latest versions of Groovy and live on the bleeding edge, you can use our snapshot builds
(https://oss.jfrog.org/oss-snapshot-local/org/codehaus/groovy). As soon as a build succeeds on our continuous integration server
a snapshot is deployed to Artifactory’s OSS snapshot repository.
Prerequisites
Groovy 2.5 requires Java 6+ with full support up to Java 8. There are currently some known issues for some aspects when using
Java 9 snapshots. The groovy-nio module requires Java 7+. Using Groovy’s invokeDynamic features require Java 7+ but we
recommend Java 8.
The Groovy CI server is also useful to look at to con rm supported Java versions for di erent Groovy releases. The test suite
(getting close to 10000 tests) runs for the currently supported streams of Groovy across all the main versions of Java each stream
supports.
Stable Release
http://docs.groovy-lang.org/latest/html/documentation/ 187/502
1/6/2019 Groovy Language Documentation
Gradle Maven Explanation
To use the InvokeDynamic (invokedynamic-support.html) version of the jars just append ':indy' for Gradle or
<classi er>indy</classi er> for Maven.
$ source "$HOME/.sdkman/bin/sdkman-init.sh"
After installation is complete and you’ve made it your default version, test it with:
$ groovy -version
Installation on Mac OS X
MacPorts
If you’re on MacOS and have MacPorts (http://www.macports.org) installed, you can run:
Homebrew
If you’re on MacOS and have Homebrew (http://mxcl.github.com/homebrew) installed, you can run:
http://docs.groovy-lang.org/latest/html/documentation/ 188/502
1/6/2019 Groovy Language Documentation
brew install groovy
Installation on Windows
If you’re on Windows, you can also use the NSIS Windows installer (TODO-Windows+NSIS-Installer).
Other Distributions
You may download other distributions of Groovy from this site (https://bintray.com/groovy/maven).
Source Code
If you prefer to live on the bleeding edge, you can also grab the source code from GitHub (https://github.com/apache/groovy).
IDE plugin
If you are an IDE user, you can just grab the latest IDE plugin (tools-ide.html) and follow the plugin installation instructions.
First, Download a binary distribution of Groovy and unpack it into some le on your local le system.
Set your GROOVY_HOME environment variable to the directory you unpacked the distribution.
Set your JAVA_HOME environment variable to point to your JDK. On OS X this is /Library/Java/Home , on other unixes its
often /usr/java etc. If you’ve already installed tools like Ant or Maven you’ve probably already done this step.
You should now have Groovy installed properly. You can test this by typing the following in a command shell:
groovysh
Which should create an interactive groovy shell where you can type Groovy statements. Or to run the Swing interactive console
type:
groovyConsole
groovy
Here we list all the major di erences between Java and Groovy.
java.io.*
java.lang.*
java.math.BigDecimal
java.math.BigInteger
java.net.*
java.util.*
groovy.lang.*
groovy.util.*
3.2.2. Multi-methods
http://docs.groovy-lang.org/latest/html/documentation/ 189/502
1/6/2019 In Groovy, the methods which will be invoked are chosen Groovy
at runtime. This isDocumentation
Language called runtime dispatch or multi-methods. It means
that the method will be chosen based on the types of the arguments at runtime. In Java, this is the opposite: methods are chosen
at compile time, based on the declared types.
The following code, written as Java code, can be compiled in both Java and Groovy, but it will behave di erently:
method( arg) {
1;
}
method( arg) {
2;
}
o = "Object";
result = method(o);
assertEquals(2, result);
Whereas in Groovy:
assertEquals(1, result);
That is because Java will use the static information type, which is that o is declared as an Object , whereas Groovy will choose at
runtime, when the method is actually called. Since it is called with a String , then the String version is called.
[] array = { 1, 2, 3}
[] array = [1,2,3]
{
name
}
Instead, it is used to create a property, that is to say a private eld, an associated getter and an associated setter.
{
@PackageScope name
}
http://docs.groovy-lang.org/latest/html/documentation/ 190/502
1/6/2019 Groovy Language Documentation
file = .get("/path/to/file");
charset = .forName("UTF-8");
( reader = .newBufferedReader(file, charset)) {
line;
((line = reader.readLine()) != ) {
.out.println(line);
}
} ( e) {
e.printStackTrace();
}
('/path/to/file').eachLine('UTF-8') {
println it
}
The implementation of anonymous inner classes and nested classes follows the Java lead, but you should not take
out the Java Language Spec and keep shaking the head about things that are di erent. The implementation done
looks much like what we do for groovy.lang.Closure , with some bene ts and some di erences. Accessing
private elds and methods for example can become a problem, but on the other hand local variables don’t have
to be nal.
A {
B {}
}
A.B()
The usage of static inner classes is the best supported one. If you absolutely need an inner class, you should make it a static one.
java.util.concurrent.
java.util.concurrent.
called = (1)
timer = ()
timer.schedule( () {
run() {
called.countDown()
}
}, 0)
called.await(10, .SECONDS)
Y {
X {}
X foo() {
X();
}
X createX(Y y) {
y. X();
}
}
Groovy doesn’t support the y.new X() syntax. Instead, you have to write new X(y) , like in the code below:
Y {
X {}
X foo() {
X()
}
X createX(Y y) {
X(y)
}
}
Caution though, Groovy supports calling methods with one parameter without giving an argument. The parameter
will then have the value null. Basically the same rules apply to calling a constructor. There is a danger that you will
write new X() instead of new X(this) for example. Since this might also be the regular way we have not yet found a
good way to prevent this problem.
3.2.7. Lambdas
Java 8 supports lambdas and method references:
Java 8 lambdas can be more or less considered as anonymous inner classes. Groovy doesn’t support that syntax, but has closures
instead:
3.2.8. GStrings
As double-quoted string literals are interpreted as GString values, Groovy may fail with compile error or produce subtly di erent
code if a class with String literal containing a dollar character is compiled with Groovy and Java compiler.
While typically, Groovy will auto-cast between GString and String if an API declares the type of a parameter, beware of Java
APIs that accept an Object parameter and then check the actual type.
'c'.getClass()==
"c".getClass()==
"c${1}".getClass()
Groovy will automatically cast a single-character String to char only when assigning to a variable of type char . When calling
methods with arguments of type char we need to either cast explicitly or make sure the value has been cast in advance.
http://docs.groovy-lang.org/latest/html/documentation/ 192/502
1/6/2019 Groovy Language Documentation
a='a'
.digit(a, 16)==10 : 'But Groovy does boxing'
.digit(( ) 'a', 16)==10
{
.digit('a', 16)==10
: 'Need explicit cast'
} ( e) {
}
Groovy supports two styles of casting and in the case of casting to char there are subtle di erences when casting a multi-char
strings. The Groovy style cast is more lenient and will take the rst character, while the C-style cast will fail with exception.
i
m(i)
m( l) { 1
m( i) { 2
1 This is the method that Java would call, since widening has precedence over unboxing.
2 This is the method Groovy actually calls, since all primitive references use their wrapper class.
3.2.11. Behaviour of ==
In Java == means equality of primitive types or identity for objects. In Groovy == translates to a.compareTo(b)==0 , if they are
Comparable , and a.equals(b) otherwise. To check for identity, there is is . E.g. a.is(b) .
3.2.12. Conversions
Java does automatic widening and narrowing conversions (https://docs.oracle.com/javase/specs/jls/se7/html/jls-5.html).
Converts to
Converts from boolean byte short char int long oat double
boolean - N N N N N N N
http://docs.groovy-lang.org/latest/html/documentation/ 193/502
1/6/2019 Groovy Language Documentation
byte N - Y C Y Y Y Y
short N C - C Y Y Y Y
char N C C - Y Y Y Y
int N C C C - Y T Y
long N C C C C - T T
oat N C C C C C - Y
double N C C C C C C -
* 'Y' indicates a conversion Java can make, 'C' indicates a conversion Java can make when there is an explicit cast, 'T` indicates a
conversion Java can make but data is truncated, 'N' indicates a conversion Java can’t make.
Converts to
Converts boolean Boolean byte Byte short Short char Character int Integer long Long BigInteger oat
from
boolean - B N N N N N N N N N N N N
Boolean B - N N N N N N N N N N N N
byte T T - B Y Y Y D Y Y Y Y Y Y
Byte T T B - Y Y Y D Y Y Y Y Y Y
short T T D D - B Y D Y Y Y Y Y Y
Short T T D T B - Y D Y Y Y Y Y Y
char T T Y D Y D - D Y D Y D D Y
Character T T D D D D D - D D D D D D
int T T D D D D Y D - B Y Y Y Y
Integer T T D D D D Y D B - Y Y Y Y
long T T D D D D Y D D D - B Y T
Long T T D D D T Y D D T B - Y T
http://docs.groovy-lang.org/latest/html/documentation/ 194/502
1/6/2019 Groovy Language Documentation
BigInteger T T D D D D D D D D D D - D
oat T T D D D D T D D D D D D -
Float T T D T D T T D D T D T D B
double T T D D D D T D D D D D D D
Double T T D T D T T D D T D T D D
BigDecimal T T D D D D D D D D D D D T
*
'Y' indicates a conversion Groovy can make, 'D' indicates a conversion Groovy can make when compiled dynamically or explicitly
cast, 'T` indicates a conversion Groovy can make but data is truncated, 'B' indicates a boxing/unboxing operation, 'N' indicates a
conversion Groovy can’t make.
The truncation uses Groovy Truth when converting to boolean / Boolean . Converting from a number to a character casts the
Number.intvalue() to char . Groovy constructs BigInteger and BigDecimal using Number.doubleValue() when
converting from a Float or Double , otherwise it constructs using toString() . Other conversions have their behavior de ned
by java.lang.Number .
as
def
in
trait
The following section focuses on sample idiomatic constructs using helper methods available above but is not meant to be a
complete description of all available methods. For that, please read the GDK API (gdk.html).
Reading les
http://docs.groovy-lang.org/latest/html/documentation/ 195/502
1/6/2019 As a rst example, let’s see how you would print all lines of a text Language
Groovy le in Groovy:
Documentation
The eachLine method is a method added to the File class automatically by Groovy and has many variants, for example if you
need to know the line number, you can use this variant:
If for whatever reason the an exception is thrown in the eachLine body, the method makes sure that the resource is properly
closed. This is true for all I/O resource methods that Groovy adds.
For example in some cases you will prefer to use a Reader , but still bene t from the automatic resource management from
Groovy. In the next example, the reader will be closed even if the exception occurs:
count = 0, MAXSIZE = 3
(baseDir,"haiku.txt").withReader { reader ->
(reader.readLine()) {
(++count > MAXSIZE) {
('Haiku should only have 3 verses')
}
}
}
Should you need to collect the lines of a text le into a list, you can do:
Or you can even leverage the as operator to get the contents of the le into an array of lines:
How many times did you have to get the contents of a le into a byte[] and how much code does it require? Groovy makes it
very easy actually:
[] contents = file.bytes
Working with I/O is not limited to dealing with les. In fact, a lot of operations rely on input/output streams, hence why Groovy
adds a lot of support methods to those, as you can see in the documentation (http://docs.groovy-lang.org/latest/html/groovy-
jdk/java/io/InputStream.html).
= (baseDir,'haiku.txt').newInputStream()
// do something ...
.close()
However you can see that it requires you to deal with closing the inputstream. In Groovy it is in general a better idea to use the
withInputStream idiom that will take care of that for you:
Writing les
http://docs.groovy-lang.org/latest/html/documentation/ 196/502
1/6/2019 Of course in some cases you won’t want to read but writeGroovy
a le. One of the options
Language is to use a Writer :
Documentation
But for such a simple example, using the << operator would have been enough:
Of course we do not always deal with text contents, so you could use the Writer or directly write bytes as in this example:
file.bytes = [66,22,11]
Of course you can also directly deal with output streams. For example, here is how you would create an output stream to write
into a le:
os = (baseDir,'data.bin').newOutputStream()
// do something ...
os.close()
However you can see that it requires you to deal with closing the output stream. Again it is in general a better idea to use the
withOutputStream idiom that will handle the exceptions and close the stream in any case:
Traversing le trees
In scripting contexts it is a common task to traverse a le tree in order to nd some speci c les and do something with them.
Groovy provides multiple methods to do this. For example you can perform something on all les of a directory:
println file.name
}
dir.eachFileMatch(~/.*\.txt/) { file -> 2
println file.name
}
Often you will have to deal with a deeper hierarchy of les, in which case you can use eachFileRecurse :
println file.name
}
println file.name
}
1 executes the closure code on each le or directory found in the directory, recursively
2 executes the closure code only on les, but recursively
http://docs.groovy-lang.org/latest/html/documentation/ 197/502
1/6/2019 For more complex traversal techniques you can use the traverse method,Documentation
Groovy Language which requires you to set a special ag indicating
what to do with the traversal:
} {
println file.name
.CONTINUE 2
1 if the current le is a directory and its name is bin , stop the traversal
2 otherwise print the le name and continue
b =
message = 'Hello from Groovy'
// Serialize data into a file
file.withDataOutputStream { ->
.writeBoolean(b)
.writeUTF(message)
}
// ...
// Then read it back
file.withDataInputStream { input ->
input.readBoolean() == b
input.readUTF() == message
}
And similarily, if the data you want to serialize implements the Serializable interface, you can proceed with an object output
stream, as illustrated here:
p = (name:'Bob', age:76)
// Serialize data into a file
file.withObjectOutputStream { ->
.writeObject(p)
}
// ...
// Then read it back
file.withObjectInputStream { input ->
p2 = input.readObject()
p2.name == p.name
p2.age == p.age
}
Groovy provides a simple way to execute command line processes. Simply write the command line as a string and call the
execute() method. E.g., on a *nix machine (or a windows machine with appropriate *nix commands installed), you can execute
this:
http://docs.groovy-lang.org/latest/html/documentation/ 198/502
1/6/2019 1 executes the ls command in an external process Groovy Language Documentation
2 consume the output of the command and retrieve the text
The execute() method returns a java.lang.Process instance which will subsequently allow the in/out/err streams to be
processed and the exit value from the process to be inspected etc.
e.g. here is the same command as above but we will now process the resulting stream a line at a time:
println line 3
It is worth noting that in corresponds to an input stream to the standard output of the command. out will refer to a stream
where you can send data to the process (its standard input).
Remember that many commands are shell built-ins and need special handling. So if you want a listing of les in a directory on a
Windows machine and write:
process = "dir".execute()
println "${process.text}"
you will receive an IOException saying Cannot run program "dir": CreateProcess error=2, The system cannot nd the le
speci ed.
This is because dir is built-in to the Windows shell ( cmd.exe ) and can’t be run as a simple executable. Instead, you will need to
write:
Also, because this functionality currently makes use of java.lang.Process undercover, the de ciencies of that class must be
taken into consideration. In particular, the javadoc for this class says:
Because some native platforms only provide limited bu er size for standard input and output streams, failure to promptly
write the input stream or read the output stream of the subprocess may cause the subprocess to block, and even deadlock
Because of this, Groovy provides some additional helper methods which make stream handling for processes easier.
Here is how to gobble all of the output (including the error stream output) from your process:
There are also variations of consumeProcessOutput that make use of StringBuffer , InputStream , OutputStream etc… For a
complete list, please read the GDK API for java.lang.Process (http://docs.groovy-lang.org/latest/html/groovy-
jdk/java/lang/Process.html)
In addition, these is a pipeTo command (mapped to | to allow overloading) which lets the output stream of one process be fed
into the input stream of another process.
Pipes in action
http://docs.groovy-lang.org/latest/html/documentation/ 199/502
1/6/2019 Groovy Language Documentation
proc1 = 'ls'.execute()
proc2 = 'tr -d o'.execute()
proc3 = 'tr -d e'.execute()
proc4 = 'tr -d i'.execute()
proc1 | proc2 | proc3 | proc4
proc4.waitFor()
(proc4.exitValue()) {
println proc4.err.text
} {
println proc4.text
}
Consuming errors
sout = ()
serr = ()
proc2 = 'tr -d o'.execute()
proc3 = 'tr -d e'.execute()
proc4 = 'tr -d i'.execute()
proc4.consumeProcessOutput(sout, serr)
proc2 | proc3 | proc4
[proc2, proc3].each { it.consumeProcessErrorStream(serr) }
proc2.withWriter { writer ->
writer << 'testfile.groovy'
}
proc4.waitForOrKill(1000)
println "Standard output: $sout"
println "Standard error: $serr"
Lists
List literals
You can create lists as follows. Notice that [] is the empty list expression.
list = [5, 6, 7, 8]
list. (2) == 7
list[2] == 7
list java.util.
emptyList = []
emptyList.size() == 0
emptyList.add(5)
emptyList.size() == 1
list[2] = 9
list == [5, 6, 9, 8,] // trailing comma OK
} (e) {
e
}
Iterating on a list
Iterating on elements of a list is usually done calling the each and eachWithIndex methods, which execute code on each item of
a list:
[1, 2, 3].each {
println "Item: $it" // `it` is an implicit parameter corresponding to the current element
}
['a', 'b', 'c'].eachWithIndex { it, i -> // `it` is the current element, while `i` is the index
println "$i: $it"
}
In addition to iterating, it is often useful to create a new list by transforming each of its elements into something else. This
operation, often called mapping, is done in Groovy thanks to the collect method:
list = [0]
// it is possible to give `collect` the list which collects the elements
[1, 2, 3].collect(list) { it * 2 } == [0, 2, 4, 6]
list == [0, 2, 4, 6]
Manipulating lists
Filtering and searching
http://docs.groovy-lang.org/latest/html/documentation/ 201/502
1/6/2019 The Groovy development kit (http://www.groovy-lang.org/gdk.html) contains
Groovy Language a lot of methods on collections that enhance the
Documentation
standard collections with pragmatic methods, some of which are illustrated here:
[1, 2, 3].every { it < 5 } // returns true if all elements match the predicate
![1, 2, 3].every { it < 3 }
[1, 2, 3].any { it > 2 } // returns true if any element matches the
predicate
![1, 2, 3].any { it > 3 }
And here is idiomatic Groovy code for nding the maximum and minimum in a collection:
http://docs.groovy-lang.org/latest/html/documentation/ 202/502
1/6/2019 Groovy Language Documentation
mc = { a, b -> a == b ? 0 : (a < b ? -1 : 1) }
list.max(mc2) == -13
list.min(mc2) == -1
list = []
list.empty
list << 5
list.size() == 1
http://docs.groovy-lang.org/latest/html/documentation/ 203/502
1/6/2019 Groovy Language Documentation
[1, 2] + 3 + [4, 5] + 6 == [1, 2, 3, 4, 5, 6]
// equivalent to calling the `plus` method
[1, 2].plus(3).plus([4, 5]).plus(6) == [1, 2, 3, 4, 5, 6]
a = [1, 2, 3]
a += 4 // creates a new list and assigns it to `a`
a += [5, 6]
a == [1, 2, 3, 4, 5, 6]
list = [1, 2]
list.add(3)
list.addAll([5, 4])
list == [1, 2, 3, 5, 4]
list = [1, 2]
list.add(1, 3) // add 3 just before index 1
list == [1, 3, 2]
It is however important that the + operator on a list is not mutating. Compared to << , it will create a new list, which is often not
what you want and can lead to performance issues.
The Groovy development kit (http://www.groovy-lang.org/gdk.html) also contains methods allowing you to easily remove
elements from a list by value:
list = [1,2,3,4,3,2,1]
list -= 3 // creates a new list by removing `3` from the original one
list == [1,2,4,2,1]
( list -= [2,4] ) == [1,1]
It is also possible to remove an element by passing its index to the remove method, in which case the list is mutated:
list = ['a','b','c','d','e','f','b','b','a']
list.remove(2) == 'c' // remove the third element, and return it
list == ['a','b','d','e','f','b','b','a']
In case you only want to remove the rst element having the same value in a list, instead of removing all elements, you can call
the remove method passing the value:
list= ['a','b','c','b','b']
list.remove('c') // remove 'c', and return true because element removed
list.remove('b') // remove first 'b', and return true because element removed
http://docs.groovy-lang.org/latest/html/documentation/ 204/502
1/6/2019 As you can see, there are two remove methods available.Groovy
One that takes anDocumentation
Language integer and removes an element by its index, and
another that will remove the rst element that matches the passed value. So what should we do when we have a list of integers?
In this case, you may wish to use removeAt to remove an element by its index, and removeElement to remove the rst element
that matches a value.
list = [1,2,3,4,5,6,2,2,1]
Of course, removeAt and removeElement will work with lists of any type.
Additionally, removing all the elements in a list can be done by calling the clear method:
list= ['a',2,'c',4]
list.clear()
list == []
Set operations
The Groovy development kit (http://www.groovy-lang.org/gdk.html) also includes methods making it easy to reason on sets:
[1,2,4,6,8,10,12].intersect([1,3,6,9,12]) == [1,6,12]
[1,2,3].disjoint( [4,6,9] )
![1,2,3].disjoint( [2,4,6] )
Sorting
Working with collections often implies sorting. Groovy o ers a variety of options to sort lists, from using closures to comparators,
as in the following examples:
http://docs.groovy-lang.org/latest/html/documentation/ 205/502
1/6/2019 Groovy Language Documentation
[6, 3, 9, 2, 7, 1, 5].sort() == [1, 2, 3, 5, 6, 7, 9]
// JDK 8+ only
// list2.sort(mc)
// assert list2 == [-1, 2, 3, 4, 5, -6, 7, -9, 11, -13]
.sort(list3)
list3 == [-7, -3, 1, 2, 5, 6, 9]
.sort(list3, mc)
list3 == [1, 2, -3, 5, 6, -7, 9]
Duplicating elements
The Groovy development kit (http://www.groovy-lang.org/gdk.html) also takes advantage of operator overloading to provide
methods allowing duplication of elements of a list:
[1, 2, 3] * 3 == [1, 2, 3, 1, 2, 3, 1, 2, 3]
[1, 2, 3].multiply(2) == [1, 2, 3, 1, 2, 3]
.nCopies(3, 'b') == ['b', 'b', 'b']
// nCopies from the JDK has different semantics than multiply for lists
.nCopies(2, [1, 2]) == [[1, 2], [1, 2]] //not [1,2,1,2]
Maps
Map literals
In Groovy, maps (also known as associative arrays) can be created using the map literal syntax: [:] :
emptyMap = [:]
emptyMap.size() == 0
emptyMap.put("foo", 5)
emptyMap.size() == 1
emptyMap. ("foo") == 5
Map keys are strings by default: [a:1] is equivalent to ['a':1] . This can be confusing if you de ne a variable named a and
that you want the value of a to be the key in your map. If this is the case, then you must escape the key by adding parenthesis,
like in the following example:
http://docs.groovy-lang.org/latest/html/documentation/ 206/502
1/6/2019 Groovy Language Documentation
a = 'Bob'
ages = [a: 43]
ages['Bob'] == // `Bob` is not found
ages['a'] == 43 // because `a` is a literal!
In addition to map literals, it is possible, to get a new copy of a map, to clone it:
map = [
simple : 123,
complex: [a: 1, b: 2]
]
map2 = map.clone()
map2. ('simple') == map. ('simple')
map2. ('complex') == map. ('complex')
map2. ('complex').put('c', 3)
map. ('complex'). ('c') == 3
The resulting map is a shallow copy of the original one, as illustrated in the previous example.
emptyMap = [:]
emptyMap.size() == 0
emptyMap.foo = 5
emptyMap.size() == 1
emptyMap.foo == 5
Note: by design map.foo will always look for the key foo in the map. This means foo.class will return null on a map that
doesn’t contain the class key. Should you really want to know the class, then you must use getClass() :
map = [1 : 'a',
( ) : 'p',
( ): 'q',
( ) : 'x',
'null' : 'z']
map.containsKey(1) // 1 is not an identifier so used as is
map. ==
map. ==
map. ( ) == 'p'
map. ( ) == 'q'
map. == 'z'
map. ( ) == 'x'
Iterating on maps
As usual in the Groovy development kit (http://www.groovy-lang.org/gdk.html), idiomatic iteration on maps makes use of the
each and eachWithIndex methods. It’s worth noting that maps created using the map literal notation are ordered, that is to say
that if you iterate on map entries, it is guaranteed that the entries will be returned in the same order they were added in the map.
http://docs.groovy-lang.org/latest/html/documentation/ 207/502
1/6/2019 Groovy Language Documentation
map = [
: 42,
: 54,
: 33
]
Manipulating maps
Adding or removing elements
Adding an element to a map can be done either using the put method, the subscript operator or using putAll :
result = (defaults)
result.put(15, 't')
result[17] = 'u'
result.putAll(overrides)
result == [1: 'a', 2: 'z', 3: 'c', 4: 'd', 5: 'x', 13: 'x', 15: 't', 17: 'u']
Removing all the elements of a map can be done by calling the clear method:
m = [1:'a', 2:'b']
m. (1) == 'a'
m.clear()
m == [:]
Maps generated using the map literal syntax are using the object equals and hashcode methods. This means that you should
never use an object which hash code is subject to change over time, or you wouldn’t be able to get the associated value back.
It is also worth noting that you should never use a GString as the key of a map, because the hash code of a GString is not the
same as the hash code of an equivalent String :
http://docs.groovy-lang.org/latest/html/documentation/ 208/502
1/6/2019 Groovy Language Documentation
map = [1:'a', 2:'b', 3:'c']
entries = map.entrySet()
entries.each { entry ->
entry.key [1,2,3]
entry.value ['a','b','c']
}
keys = map.keySet()
keys == [1,2,3]
Mutating values returned by the view (be it a map entry, a key or a value) is highly discouraged because success of the operation
directly depends on the type of the map being manipulated. In particular, Groovy relies on collections from the JDK that in general
make no guarantee that a collection can safely be manipulated through keySet , entrySet , or values .
people = [
1: [name:'Bob', age: 32, gender: 'M'],
2: [name:'Johnny', age: 36, gender: 'M'],
3: [name:'Claire', age: 21, gender: 'F'],
4: [name:'Amy', age: 54, gender:'F']
]
// both return entries, but you can use collect to retrieve the ages for example
ageOfBob = bob.value.age
agesOfFemales = females.collect {
it.value.age
}
ageOfBob == 32
agesOfFemales == [21,54]
// but you could also use a key/pair value as the parameters of the closures
agesOfMales = people.findAll { id, person ->
person.gender == 'M'
}.collect { id, person ->
person.age
}
agesOfMales == [32, 36]
Grouping
We can group a list into a map using some criteria:
http://docs.groovy-lang.org/latest/html/documentation/ 209/502
1/6/2019 Groovy Language Documentation
['a', 7, 'b', [2, 3]].groupBy {
it.
} == [( ) : ['a', 'b'],
( ) : [7],
( ): [[2, 3]]
]
[
[name: 'Clark', city: 'London'], [name: 'Sharma', city: 'London'],
[name: 'Maradona', city: 'LA'], [name: 'Zhang', city: 'HK'],
[name: 'Ali', city: 'HK'], [name: 'Liu', city: 'HK'],
].groupBy { it.city } == [
: [[name: 'Clark', city: 'London'],
[name: 'Sharma', city: 'London']],
LA : [[name: 'Maradona', city: 'LA']],
HK : [[name: 'Zhang', city: 'HK'],
[name: 'Ali', city: 'HK'],
[name: 'Liu', city: 'HK']],
]
Ranges
Ranges allow you to create a list of sequential values. These can be used as List since Range (http://docs.groovy-
lang.org/latest/html/api/groovy/lang/Range.html) extends java.util.List
(http://docs.oracle.com/javase/8/docs/api/java/util/List.html).
Ranges de ned with the .. notation are inclusive (that is the list contains the from and to value).
Ranges de ned with the ..< notation are half-open, they include the rst value but not the last value.
// an inclusive range
range = 5..8
range.size() == 4
range. (2) == 7
range[2] == 7
range java.util.
range.contains(5)
range.contains(8)
Note that int ranges are implemented e ciently, creating a lightweight Java object containing a from and to value.
Ranges can be used for any Java object which implements java.lang.Comparable for comparison and also have methods next()
and previous() to return the next / previous item in the range. For example, you can create a range of String elements:
http://docs.groovy-lang.org/latest/html/documentation/ 210/502
1/6/2019 Groovy Language Documentation
// an inclusive range
range = 'a'..'d'
range.size() == 4
range. (2) == 'c'
range[2] == 'c'
range java.util.
range.contains('a')
range.contains('d')
!range.contains('e')
(i 1..10) {
println "Hello ${i}"
}
but alternatively you can achieve the same e ect in a more Groovy idiomatic style, by iterating a range with each method:
(1..10).each { i ->
println "Hello ${i}"
}
(years) {
1..10: interestRate = 0.076; ;
11..25: interestRate = 0.052; ;
: interestRate = 0.037;
}
GPath support
Thanks to the support of property notation for both lists and maps, Groovy provides syntactic sugar making it really easy to deal
with nested collections, as illustrated in the following examples:
Spread operator
The spread operator can be used to "inline" a collection into another. It is syntactic sugar which often avoids calls to putAll and
facilitates the realization of one-liners:
http://docs.groovy-lang.org/latest/html/documentation/ 211/502
1/6/2019 Groovy Language Documentation
[ 'z': 900,
*: ['a': 100, 'b': 200], 'a': 300] == ['a': 300, 'b': 200, 'z': 900]
//spread map notation in map definition
[*: [3: 3, *: [5: 5]], 7: 7] == [3: 3, 5: 5, 7: 7]
f = { m, i, j, k -> [m, i, j, k] }
//using spread map notation with mixed unnamed and named arguments
f('e': 100, *[4, 5], *: ['a': 10, 'b': 20, 'c': 30], 6) ==
[["e": 100, "b": 20, "c": 30, "a": 10], 4, 5, 6]
{
name
age
}
persons = [ (name:'Hugo', age:17), (name:'Sandra',age:19)]
[17, 19] == persons*.age
x == 'c'
x. ==
= text[5..10]
== 'cheese'
list = 100..200
= list[1, 3, 20..25, 33]
== [101, 103, 120, 121, 122, 123, 124, 125, 133]
The subscript operator can be used to update an existing collection (for collection type which are not immutable):
list = ['a','x','x','d']
list[1..2] = ['b','c']
list == ['a','b','c','d']
It is worth noting that negative indices are allowed, to extract more easily from the end of a collection:
http://docs.groovy-lang.org/latest/html/documentation/ 212/502
1/6/2019 Groovy Language Documentation
text = "nice cheese gromit!"
x = text[-1]
x == "!"
You can use negative indices to count from the end of the List, array, String etc.
name = text[-7..-2]
name == "gromit"
Eventually, if you use a backwards range (the starting index is greater than the end index), then the answer is reversed.
In particular, we invite you to read the Groovy development kit (http://www.groovy-lang.org/gdk.html) API docs and speci cally:
You can access the properties of a Date or Calendar using the normal array index notation with the constant eld numbers
from the Calendar class as shown in the following example:
java.util. .* 1
cal = .instance
cal[YEAR] = 2000 2
cal[MONTH] = JANUARY 2
cal[DAY_OF_MONTH] = 1 2
cal[DAY_OF_WEEK] == SATURDAY 3
Groovy supports arithmetic on and iteration between Date and Calendar instances as shown in the following example:
http://docs.groovy-lang.org/latest/html/documentation/ 213/502
1/6/2019 Groovy Language Documentation
utc = .getTimeZone('UTC')
date = .parse("yyyy-MM-dd HH:mm", "2010-05-23 09:01", utc)
prev = date - 1
= date + 1
diffInDays = - prev
diffInDays == 2
count = 0
prev.upto( ) { count++ }
count == 3
You can parse strings into dates and output dates into formatted strings:
orig = '2000-01-01'
newYear = .parse('yyyy-MM-dd', orig)
newYear[DAY_OF_WEEK] == SATURDAY
newYear.format('yyyy-MM-dd') == orig
newYear.format('dd/MM/yyyy') == '01/01/2000'
You can also create a new Date or Calendar based on an existing one:
Method Description
http://docs.groovy-lang.org/latest/html/documentation/ 214/502
1/6/2019 Groovy Language Documentation
Method Description
For parsing, Groovy adds a static parse method to many of the JSR 310 types. The method takes two arguments: the value to be
formatted and the pattern to use. The pattern is de ned by the java.time.format.DateTimeFormatter API
(https://docs.oracle.com/javase/8/docs/api/java/time/format/DateTimeFormatter.html). As an example:
Note that these parse methods have a di erent argument ordering than the static parse method Groovy added to
java.util.Date . This was done to be consistent with the existing parse methods of the Date/Time API.
Manipulating date/time
http://docs.groovy-lang.org/latest/html/documentation/ 215/502
1/6/2019 Groovy Language Documentation
aprilFools = .of(2018, .APRIL, 1)
Groovy provides additional plus and minus methods that accept an integer argument, enabling the above to be rewritten more
succinctly:
The unit of these integers depends on the JSR 310 type operand. As evident above, integers used with ChronoLocalDate types
like LocalDate have a unit of days
(https://docs.oracle.com/javase/8/docs/api/java/time/temporal/ChronoUnit.html#DAYShttp://days). Integers used with Year and
YearMonth have a unit of years (https://docs.oracle.com/javase/8/docs/api/java/time/temporal/ChronoUnit.html#YEARS) and
months (https://docs.oracle.com/javase/8/docs/api/java/time/temporal/ChronoUnit.html#MONTHS), respectively. All other types
have a unit of seconds (https://docs.oracle.com/javase/8/docs/api/java/time/temporal/ChronoUnit.html#SECONDS), such as
LocalTime , for instance:
year = .of(2000)
--year // decrement by one year
year.value == 1999
Negation
The Duration and Period types represent a negative or positive length of time. These can be negated with the unary -
operator.
duration = .ofSeconds(-15)
negated = -duration
negated.seconds == 15
period = .ofYears(2).withMonths(4).withDays(6)
period[ .YEARS] == 2
period[ .MONTHS] == 4
period[ .DAYS] == 6
start = .now()
= start + 6 // 6 days later
(start.. ).each { date ->
println date.dayOfWeek
}
The upto method will accomplish the same as the range in the above example. The upto method iterates from the earlier start
value (inclusive) to the later end value (also inclusive), calling the closure with the incremented value once per iteration.
start = .now()
= start + 6 // 6 days later
start.upto( ) { date ->
println date.dayOfWeek
}
The downto method iterates in the opposite direction, from a later start value to an earlier end value.
The unit of iteration for upto , downto , and ranges is the same as the unit for addition and subtraction: LocalDate iterates by
one day at a time, YearMonth iterates by one month, Year by one year, and everything else by one second. Both methods also
support an optional a TemporalUnit argument to change the unit of iteration.
Consider the following example, where March 1st, 2018 is iterated up to March 2nd, 2018 using an iteration unit of months
(https://docs.oracle.com/javase/8/docs/api/java/time/temporal/ChronoUnit.html#MONTHS).
iterationCount = 0
start.upto( , .MONTHS) { date ->
println date
++iterationCount
}
iterationCount == 1
Since the start date is inclusive, the closure is called with date March 1st. The upto method then increments the date by one
month, yielding the date, April 1st. Because this date is after the speci ed end date of March 2nd, the iteration stops immediately,
having only called the closure once. This behavior is the same for the downto method except that the iteration will stop as soon
as the the value of end becomes earlier than the targeted end date.
http://docs.groovy-lang.org/latest/html/documentation/ 217/502
1/6/2019 In short, when iterating with the upto or downto methods with Language
Groovy a custom unit of iteration, the current value of iteration will never
Documentation
exceed the end value.
The left-shift operator is re exive; the order of the operands does not matter.
year = .of(2000)
month = .DECEMBER
If the value on the left-hand side of the operator is earlier than the value on the right-hand side, the result is positive. If the left-
hand side is later than the right-hand side, the result is negative:
Most JSR types have been tted with toDate() and toCalendar() methods for converting to relatively equivalent
java.util.Date and java.util.Calendar values. Both ZoneId and ZoneOffset have been given a toTimeZone() method
for converting to java.util.TimeZone .
http://docs.groovy-lang.org/latest/html/documentation/ 218/502
1/6/2019 Groovy Language Documentation
// LocalDate to java.util.Date
valentines = .of(2018, .FEBRUARY, 14)
valentines.toDate().format('MMMM dd, yyyy') == 'February 14, 2018'
// LocalTime to java.util.Date
noon = .of(12, 0, 0)
noon.toDate().format('HH:mm:ss') == '12:00:00'
// ZoneId to java.util.TimeZone
newYork = .of('America/New_York')
newYork.toTimeZone() == .getTimeZone('America/New_York')
// ZonedDateTime to java.util.Calendar
valAtNoonInNY = .of(valentines, noon, newYork)
valAtNoonInNY.toCalendar().getTimeZone().toZoneId() == newYork
Nanosecond values are truncated to milliseconds. A LocalTime , for example, with a ChronoUnit.NANOS value of 999,999,999
nanoseconds translates to 999 milliseconds.
When converting the "local" types ( LocalDate , LocalTime , and LocalDateTime ), the time zone of the returned Date or
Calendar will be the system default.
When converting a time-only type ( LocalTime or OffsetTime ), the year/month/day of the Date or Calendar is set to the
current date.
When converting a date-only type ( LocalDate ), the time value of the Date or Calendar will be cleared, i.e. 00:00:00.000 .
When converting an OffsetDateTime to a Calendar , only the hours and minutes of the ZoneOffset convey into the
corresponding TimeZone . Fortunately, Zone O sets with non-zero seconds are rare.
Groovy has added a number of methods to Date and Calendar for converting into the various JSR 310 types:
legacy.toLocalDate() == .of(2010, 4, 3)
legacy.toLocalTime() == .of(10, 30, 58, 999_000_000) // 999M ns = 999ms
legacy.toOffsetTime().hour == 10
legacy.toYear() == .of(2010)
legacy.toMonth() == .APRIL
legacy.toDayOfWeek() == .SATURDAY
legacy.toMonthDay() == .of( .APRIL, 3)
legacy.toYearMonth() == .of(2010, .APRIL)
legacy.toLocalDateTime().year == 2010
legacy.toOffsetDateTime().dayOfMonth == 3
legacy.toZonedDateTime().zone == .systemDefault()
Con gSlurper
ConfigSlurper is a utility class for reading con guration les de ned in the form of Groovy scripts. Like it is the case with Java
*.properties les, ConfigSlurper allows a dot notation. But in addition, it allows for Closure scoped con guration values and
arbitrary object types.
config = ().parse('''
app.date = new Date() 1
app.age = 42
app { 2
name = "Test${42}"
}
''')
config.app.date
config.app.age == 42
config.app.name == 'Test42'
http://docs.groovy-lang.org/latest/html/documentation/ 219/502
1/6/2019 1 Usage of the dot notation Groovy Language Documentation
As can be seen in the above example, the parse method can be used to retrieve groovy.util.ConfigObject instances. The
ConfigObject is a specialized java.util.Map implementation that either returns the con gured value or a new
ConfigObject instance but never null .
config = ().parse('''
app.date = new Date()
app.age = 42
app.name = "Test${42}"
''')
config.test != 1
1 config.test has not been speci ed yet it returns a ConfigObject when being called.
In the case of a dot being part of a con guration variable name, it can be escaped by using single or double quotes.
config = ().parse('''
app."person.age" = 42
''')
config.app."person.age" == 42
In addition, ConfigSlurper comes with support for environments . The environments method can be used to hand over a
Closure instance that itself may consist of a several sections. Let’s say we wanted to create a particular con guration value for the
development environment. When creating the ConfigSlurper instance we can use the ConfigSlurper(String) constructor to
specify the target environment.
config = ('development').parse('''
environments {
development {
app.port = 8080
}
test {
app.port = 8082
}
production {
app.port = 80
}
}
''')
config.app.port == 8080
The ConfigSlurper environments aren’t restricted to any particular environment names. It solely depends on
the ConfigSlurper client code what value are supported and interpreted accordingly.
The environments method is built-in but the registerConditionalBlock method can be used to register other method names
in addition to the environments name.
http://docs.groovy-lang.org/latest/html/documentation/ 220/502
1/6/2019 Groovy Language Documentation
slurper = ()
slurper.registerConditionalBlock('myProject', 'developers') 1
config = slurper.parse('''
sendMail = true
myProject {
developers {
sendMail = false
}
}
''')
!config.sendMail
For Java integration purposes the toProperties method can be used to convert the ConfigObject to a
java.util.Properties object that might be stored to a *.properties text le. Be aware though that the con guration values
are converted to String instances during adding them to the newly created Properties instance.
config = ().parse('''
app.date = new Date()
app.age = 42
app {
name = "Test${42}"
}
''')
properties = config.toProperties()
properties."app.date"
properties."app.age" == '42'
properties."app.name" == 'Test42'
Expando
The Expando class can be used to create a dynamically expandable object. Despite its name it does not use the
ExpandoMetaClass underneath. Each Expando object represents a standalone, dynamically-crafted instance that can be
extended with properties (or methods) at runtime.
expando = ()
expando.name = 'John'
expando.name == 'John'
A special case occurs when a dynamic property registers a Closure code block. Once being registered it can be invoked as it
would be done with a method call.
expando = ()
expando.toString = { -> 'John' }
expando.say = { s -> "John says: ${s}" }
expando == 'John'
expando.say('Hi') == 'John says: Hi'
Depending on the type of change that has happened, observable collections might re more specialized PropertyChangeEvent
types. For example, adding an element to an observable list res an ObservableList.ElementAddedEvent event.
http://docs.groovy-lang.org/latest/html/documentation/ 221/502
1/6/2019 Groovy Language Documentation
1
listener = {
(it . ) { 2
= it
}
}
observable = [1, 2, 3] 3
observable.addPropertyChangeListener(listener) 4
observable.add 42 5
elementAddedEvent = .
elementAddedEvent.changeType == . .ADDED
elementAddedEvent.index == 3
elementAddedEvent.oldValue ==
elementAddedEvent.newValue == 42
Be aware that adding an element in fact causes two events to be triggered. The rst is of type
ObservableList.ElementAddedEvent , the second is a plain PropertyChangeEvent that informs listeners about
the change of property size .
The ObservableList.ElementClearedEvent event type is another interesting one. Whenever multiple elements are removed,
for example when calling clear() , it holds the elements being removed from the list.
listener = {
(it . ) {
= it
}
}
observable = [1, 2, 3]
observable.addPropertyChangeListener(listener)
observable.clear()
elementClearedEvent = .
elementClearedEvent.values == [1, 2, 3]
observable.size() == 0
To get an overview of all the supported event types the reader is encouraged to have a look at the JavaDoc documentation or the
source code of the observable collection in use.
ObservableMap and ObservableSet come with the same concepts as we have seen for ObservableList in this section.
3.4. Metaprogramming
http://docs.groovy-lang.org/latest/html/documentation/ 222/502
1/6/2019 The Groovy language supports two avors of metaprogramming: runtime and
Groovy Language compile-time. The rst allows altering the class
Documentation
model and the behavior of a program at runtime while the second only occurs at compile-time. Both have pros and cons that we
will detail in this section.
POJO - A regular Java object whose class can be written in Java or any other language for the JVM.
POGO - A Groovy object whose class is written in Groovy. It extends java.lang.Object and implements the
groovy.lang.GroovyObject (http://docs.groovy-lang.org/2.5.5/html/gapi/index.html?groovy/lang/GroovyObject.html) interface
by default.
For every method call Groovy checks whether the object is a POJO or a POGO. For POJOs, Groovy fetches its MetaClass from the
groovy.lang.MetaClassRegistry (http://docs.groovy-lang.org/2.5.5/html/gapi/index.html?groovy/lang/MetaClassRegistry.html) and
delegates method invocation to it. For POGOs, Groovy takes more steps, as illustrated in the following gure:
GroovyObject interface
groovy.lang.GroovyObject (http://docs.groovy-lang.org/2.5.5/html/gapi/index.html?groovy/lang/GroovyObject.html) is the main
interface in Groovy as the Object class is in Java. GroovyObject has a default implementation in the
groovy.lang.GroovyObjectSupport (http://docs.groovy-lang.org/2.5.5/html/gapi/index.html?
groovy/lang/GroovyObjectSupport.html) class and it is responsible to transfer invocation to the groovy.lang.MetaClass
(http://docs.groovy-lang.org/2.5.5/html/gapi/index.html?groovy/lang/MetaClass.html) object. The GroovyObject source looks like
this:
http://docs.groovy-lang.org/latest/html/documentation/ 223/502
1/6/2019 Groovy Language Documentation
groovy.lang;
getProperty( propertyName);
getMetaClass();
setMetaClass( metaClass);
}
invokeMethod
This method is primarily intended to be used in conjunction with the GroovyInterceptable interface or an object’s MetaClass
where it will intercept all method calls.
It is also invoked when the method called is not present on a Groovy object. Here is a simple example using an overridden
invokeMethod() method:
test() {
'method exists'
}
}
someGroovyClass = ()
However, the use of invokeMethod to intercept missing methods is discouraged. In cases where the intent is to only intercept
method calls in the case of a failed method dispatch use methodMissing instead.
get/setProperty
Every read access to a property can be intercepted by overriding the getProperty() method of the current object. Here is a
simple example:
http://docs.groovy-lang.org/latest/html/documentation/ 224/502
1/6/2019 Groovy Language Documentation
{
property1 = 'ha'
field2 = 'ho'
field4 = 'hu'
getField1() {
'getHa'
}
getProperty( name) {
(name != 'field3')
metaClass.getProperty( , name) 1
'field3'
}
}
someGroovyClass = ()
someGroovyClass.field1 == 'getHa'
someGroovyClass.field2 == 'ho'
someGroovyClass.field3 == 'field3'
someGroovyClass.field4 == 'hu'
1 Forwards the request to the getter for all properties except field3 .
You can intercept write access to properties by overriding the setProperty() method:
POGO {
pogo = POGO()
pogo. = 'a'
pogo. == 'overridden'
get/setMetaClass
You can a access an object’s metaClass or set your own MetaClass implementation for changing the default interception
mechanism. For example, you can write your own implementation of the MetaClass interface and assign it to objects in order to
change the interception mechanism:
// getMetaclass
someObject.metaClass
// setMetaClass
someObject.metaClass = ()
get/setAttribute
This functionality is related to the MetaClass implementation. In the default implementation you can access elds without
invoking their getters and setters. The examples below demonstrates this approach:
http://docs.groovy-lang.org/latest/html/documentation/ 225/502
1/6/2019 Groovy Language Documentation
{
field1 = 'ha'
field2 = 'ho'
getField1() {
'getHa'
}
}
someGroovyClass = ()
POGO {
field
property1
setProperty1( property1) {
.property1 = "setProperty1"
}
}
pogo = POGO()
pogo.metaClass.setAttribute(pogo, 'field', 'ha')
pogo.metaClass.setAttribute(pogo, 'property1', 'ho')
pogo.field == 'ha'
pogo.property1 == 'ho'
methodMissing
Groovy supports the concept of methodMissing . This method di ers from invokeMethod in that it is only invoked in the case of
a failed method dispatch when no method can be found for the given name and/or the given arguments:
Typically when using methodMissing it is possible to cache the result for the next time the same method is called.
For example, consider dynamic nders in GORM. These are implemented in terms of methodMissing . The code resembles
something like this:
http://docs.groovy-lang.org/latest/html/documentation/ 226/502
1/6/2019 Groovy Language Documentation
GORM {
Notice how, if we nd a method to invoke, we then dynamically register a new method on the y using ExpandoMetaClass. This is
so that the next time the same method is called it is more e cient. This way of using methodMissing does not have the
overhead of invokeMethod and is not expensive from the second call on.
propertyMissing
Groovy supports the concept of propertyMissing for intercepting otherwise failing property resolution attempts. In the case of
a getter method, propertyMissing takes a single String argument containing the property name:
{
propertyMissing( name) { name }
}
().boo == 'boo'
The propertyMissing(String) method is only called when no getter method for the given property can be found by the Groovy
runtime.
For setter methods a second propertyMissing de nition can be added that takes an additional value argument:
{
storage = [:]
propertyMissing( name, value) { storage[name] = value }
propertyMissing( name) { storage[name] }
}
f = ()
f.foo = "bar"
f.foo == "bar"
As with methodMissing it is best practice to dynamically register new properties at runtime to improve the overall lookup
performance.
static methodMissing
Static variant of methodMissing method can be added via the ExpandoMetaClass or can be implemented at the class level with
$static_methodMissing method.
{
$static_methodMissing( name, args) {
"Missing static method name is $name"
}
}
static propertyMissing
http://docs.groovy-lang.org/latest/html/documentation/ 227/502
1/6/2019 Static variant of propertyMissing method can be addedGroovy
via theLanguage
ExpandoMetaClass or can be implemented at the class level with
Documentation
$static_propertyMissing method.
{
$static_propertyMissing( name) {
"Missing static property name is $name"
}
}
GroovyInterceptable
The groovy.lang.GroovyInterceptable (http://docs.groovy-lang.org/2.5.5/html/gapi/index.html?
groovy/lang/GroovyInterceptable.html) interface is marker interface that extends GroovyObject and is used to notify the Groovy
runtime that all methods should be intercepted through the method dispatcher mechanism of the Groovy runtime.
groovy.lang;
{
}
When a Groovy object implements the GroovyInterceptable interface, its invokeMethod() is called for any method calls.
Below you can see a simple example of an object of this type:
definedMethod() { }
The next piece of code is a test which shows that both calls to existing and non-existing methods will return the same value.
testCheckInterception() {
interception = ()
interception.definedMethod() == 'invokedMethod'
interception.someMethod() == 'invokedMethod'
}
}
We cannot use default groovy methods like println because these methods are injected into all Groovy objects
so they will be intercepted too.
If we want to intercept all method calls but do not want to implement the GroovyInterceptable interface we can implement
invokeMethod() on an object’s MetaClass . This approach works for both POGOs and POJOs, as shown by this example:
http://docs.groovy-lang.org/latest/html/documentation/ 228/502
1/6/2019 Groovy Language Documentation
{
testPOJOMetaClassInterception() {
invoking = 'ha'
invoking.metaClass.invokeMethod = { name, args ->
'invoked'
}
invoking.length() == 'invoked'
invoking.someMethod() == 'invoked'
}
testPOGOMetaClassInterception() {
entity = ('Hello')
entity.metaClass.invokeMethod = { name, args ->
'invoked'
}
Categories
There are situations where it is useful if a class not under control had additional methods. In order to enable this capability,
Groovy implements a feature borrowed from Objective-C, called Categories.
Categories are implemented with so-called category classes. A category class is special in that it needs to meet certain pre-de ned
rules for de ning extension methods.
There are a few categories that are included in the system for adding functionality to classes that make them more usable within
the Groovy environment:
groovy.time.TimeCategory (http://docs.groovy-lang.org/2.5.5/html/gapi/index.html?groovy/time/TimeCategory.html)
groovy.servlet.ServletCategory (http://docs.groovy-lang.org/2.5.5/html/gapi/index.html?groovy/servlet/ServletCategory.html)
groovy.xml.dom.DOMCategory (http://docs.groovy-lang.org/2.5.5/html/gapi/index.html?groovy/xml/dom/DOMCategory.html)
Category classes aren’t enabled by default. To use the methods de ned in a category class it is necessary to apply the scoped use
method that is provided by the GDK and available from inside every Groovy object instance:
( ) {
println 1.minute. .now 1
println 10.hours.ago
someDate = () 2
The use method takes the category class as its rst parameter and a closure code block as second parameter. Inside the
Closure access to the category methods is available. As can be seen in the example above even JDK classes like
java.lang.Integer or java.util.Date can be enriched with user-de ned methods.
A category needs not to be directly exposed to the user code, the following will also do:
http://docs.groovy-lang.org/latest/html/documentation/ 229/502
1/6/2019 Groovy Language Documentation
{
// Let's enhance JPA EntityManager without getting into the JSR committee
persistAll( em , [] entities) { //add an interface to save all
entities?.each { em.persist(it) }
}
}
transactionContext = {
em, c ->
tx = em.transaction
{
tx. ()
( ) {
c()
}
tx.commit()
} (e) {
tx.rollback()
} {
//cleanup your resource here
}
}
// user code, they always forget to close resource in exception, some even forget to commit, let's
not rely on them.
em; //probably injected
transactionContext (em) {
em.persistAll(obj1, obj2, obj3)
// let's do some logics here to make the example sensible
em.persistAll(obj2, obj4, obj6)
}
When we have a look at the groovy.time.TimeCategory class we see that the extension methods are all declared as static
methods. In fact, this is one of the requirements that must be met by category classes for its methods to be successfully added to
a class inside the use code block:
cal.setTime(date);
cal.add( .YEAR, -duration.getYears());
cal.add( .MONTH, -duration.getMonths());
cal.add( .DAY_OF_YEAR, -duration.getDays());
cal.add( .HOUR_OF_DAY, -duration.getHours());
cal.add( .MINUTE, -duration.getMinutes());
cal.add( .SECOND, -duration.getSeconds());
cal.add( .MILLISECOND, -duration.getMillis());
cal.getTime();
}
// ...
Another requirement is the rst argument of the static method must de ne the type the method is attached to once being
activated. The other arguments are the normal arguments the method will take as parameters.
Because of the parameter and static method convention, category method de nitions may be a bit less intuitive than normal
method de nitions. As an alternative Groovy comes with a @Category annotation that transforms annotated classes into
category classes at compile-time.
http://docs.groovy-lang.org/latest/html/documentation/ 230/502
1/6/2019 Groovy Language Documentation
{
number
toString() { "${number}m" }
}
@Category( )
{
getMeters() {
(number: )
}
}
( ) {
42.meters.toString() == '42m'
}
Applying the @Category annotation has the advantage of being able to use instance methods without the target type as a rst
parameter. The target type class is given as an argument to the annotation instead.
Metaclasses
As explained earlier, Metaclasses play a central role in method resolution. For every method invocation from groovy code, Groovy
will nd the MetaClass for the given object and delegate the method resolution to the metaclass via MetaClass#invokeMethod
(http://docs.groovy-lang.org/2.5.5/html/gapi/groovy/lang/MetaClass.html#invokeMethod(java.lang.Class, java.lang.Object,
java.lang.String, java.lang.Object, boolean, boolean)) which should not be confused with GroovyObject#invokeMethod
(http://docs.groovy-lang.org/2.5.5/html/gapi/groovy/lang/GroovyObject.html#invokeMethod(java.lang.String, java.lang.Object))
which happens to be a method that the metaclass may eventually call.
{}
f = ()
f.metaClass =~ / /
Custom metaclasses
You can change the metaclass of any object or class and replace with a custom implementation of the MetaClass interface
(http://docs.groovy-lang.org/2.5.5/html/gapi/index.html?groovy/lang/MetaClass.html). Usually you will want to subclass one of the
existing metaclasses MetaClassImpl , DelegatingMetaClass , ExpandoMetaClass , ProxyMetaClass , etc. otherwise you will
need to implement the complete method lookup logic. Before using a new metaclass instance you should call
groovy.lang.MetaClass#initialize() (http://docs.groovy-lang.org/2.5.5/html/gapi/groovy/lang/MetaClass.html#initialize()) otherwise
the metaclass may or may not behave as expected.
Delegating metaclass
If you only need to decorate an existing metaclass the DelegatingMetaClass simpli es that use case. The old metaclass
implementation is still accessible via super making easy to apply pretransformations to the inputs, routing to other methods and
postprocess the outputs.
http://docs.groovy-lang.org/latest/html/documentation/ 231/502
1/6/2019 Groovy Language Documentation
{ bar() { "bar" } }
{
( metaClass) { (metaClass) }
( theClass) { (theClass) }
mc = ( .metaClass)
mc.initialize()
.metaClass = mc
f = ()
f.BAR() == "BAR" // the new metaclass routes .BAR() to .bar() and uppercases the result
Magic package
It is possible to change the metaclass at startup time by giving the metaclass a specially crafted (magic) class name and package
name. In order to change the metaclass for java.lang.Integer it’s enough to put a class
groovy.runtime.metaclass.java.lang.IntegerMetaClass in the classpath. This is useful, for example, when working with
frameworks if you want to to metaclass changes before your code is executed by the framework. The general form of the magic
package is groovy.runtime.metaclass.[package].[class]MetaClass . In the example below the [package] is java.lang
and the [class] is Integer :
// file: IntegerMetaClass.groovy
groovy.runtime.metaclass.java.lang;
{
( metaClass) { (metaClass) }
( theClass) { (theClass) }
invokeMethod( , name, [] args) {
(name =~ /isBiggerThan/) {
other = name.split(/isBiggerThan/)[1].toInteger()
> other
} {
.invokeMethod( ,name, args);
}
}
}
// File testInteger.groovy
i = 10
i.isBiggerThan5()
!i.isBiggerThan15()
println i.isBiggerThan5()
By running that le with groovy -cp . testInteger.groovy the IntegerMetaClass will be in the classpath and therefore it
will become the metaclass for java.lang.Integer intercepting the method calls to isBiggerThan*() methods.
{
( metaClass) { (metaClass) }
invokeMethod( , name, [] args) {
.invokeMethod( ,name,args).toUpperCase()
}
}
f1 = ()
f2 = ()
f2.metaClass = (f2.metaClass)
f1.bar() == "bar"
f2.bar() == "BAR"
f1.metaClass =~ / /
f2.metaClass =~ / /
f1. .toString() == "class Foo"
f2. .toString() == "class Foo"
ExpandoMetaClass
Groovy comes with a special MetaClass the so-called ExpandoMetaClass . It is special in that it allows for dynamically adding or
changing methods, constructors, properties and even static methods by using a neat closure syntax.
Applying those modi cations can be especially useful in mocking or stubbing scenarios as shown in the Testing Guide.
Every java.lang.Class is supplied by Groovy with a special metaClass property that will give you a reference to an
ExpandoMetaClass instance. This instance can then be used to add methods or change the behaviour of already existing ones.
The following sections go into detail on how ExpandoMetaClass can be used in various scenarios.
Methods
Once the ExpandoMetaClass is accessed by calling the metaClass property, methods can added by using either the left shift <<
or the = operator.
Note that the left shift operator is used to append a new method. If a public method with the same name and
parameter types is declared by the class or interface, including those inherited from superclasses and
superinterfaces but excluding those added to the metaClass at runtime, an exception will be thrown. If you want
to replace a method declared by the class or interface you can use the = operator.
The operators are applied on a non-existent property of metaClass passing an instance of a Closure code block.
{
title
}
b = (title:"The Stand")
The example above shows how a new method can be added to a class by accessing the metaClass property and using the << or
= operator to assign a Closure code block. The Closure parameters are interpreted as method parameters. Parameterless
methods can be added by using the {→ …} syntax.
Properties
ExpandoMetaClass supports two mechanisms for adding or overriding properties.
Firstly, it has support for declaring a mutable property by simply assigning a value to a property of metaClass :
http://docs.groovy-lang.org/latest/html/documentation/ 233/502
1/6/2019 Groovy Language Documentation
{
title
}
Another way is to add getter and/or setter methods by using the standard mechanisms for adding instance methods.
{
title
}
.metaClass.getAuthor << {-> "Stephen King" }
b = ()
In the source code example above the property is dictated by the closure and is a read-only property. It is feasible to add an
equivalent setter method but then the property value needs to be stored for later usage. This could be done as shown in the
following example.
{
title
}
properties = .synchronizedMap([:])
This is not the only technique however. For example in a servlet container one way might be to store the values in the currently
executing request as request attributes (as is done in some cases in Grails).
Constructors
Constructors can be added by using a special constructor property. Either the << or = operator can be used to assign a
Closure code block. The Closure arguments will become the constructor arguments when the code is executed at runtime.
{
title
}
.metaClass.constructor << { title -> (title:title) }
Be careful when adding constructors however, as it is very easy to get into stack over ow troubles.
Static Methods
Static methods can be added using the same technique as instance methods with the addition of the static quali er before the
method name.
http://docs.groovy-lang.org/latest/html/documentation/ 234/502
1/6/2019 Groovy Language Documentation
{
title
}
b = .create("The Stand")
Borrowing Methods
With ExpandoMetaClass it is possible to use Groovy’s method pointer syntax to borrow methods from other classes.
{
name
}
{
borrowMoney() {
"buy house"
}
}
lender = ()
.metaClass.buyHouse = lender.&borrowMoney
p = ()
{
name = "Fred"
}
methodName = "Bob"
p = ()
"Fred" == p.name
p.changeNameToBob()
"Bob" == p.name
One application of dynamic method names can be found in the Grails web application framework. The concept of "dynamic
codecs" is implemented by using dynamic method names.
HTMLCodec Class
{
encode = { theTarget ->
.htmlEscape(theTarget.toString())
}
html = '<html><body>hello</body></html>'
'<html><body>hello</body></html>' == html.encodeAsHTML()
Runtime Discovery
At runtime it is often useful to know what other methods or properties exist at the time the method is executed.
ExpandoMetaClass provides the following methods as of this writing:
getMetaMethod
hasMetaMethod
getMetaProperty
hasMetaProperty
Why can’t you just use re ection? Well because Groovy is di erent, it has the methods that are "real" methods and methods that
are available only at runtime. These are sometimes (but not always) represented as MetaMethods. The MetaMethods tell you
what methods are available at runtime, thus your code can adapt.
GroovyObject Methods
Another feature of ExpandoMetaClass is that it allows to override the methods invokeMethod , getProperty and
setProperty , all of them can be found in the groovy.lang.GroovyObject class.
{
invokeMe() { "foo" }
}
stf = ()
"foo" == stf.invokeMe()
"bar" == stf.doStuff()
The rst step in the Closure code is to lookup the MetaMethod for the given name and arguments. If the method can be found
everything is ne and it is delegated to. If not, a dummy value is returned.
A MetaMethod is a method that is known to exist on the MetaClass whether added at runtime or at compile-
time.
http://docs.groovy-lang.org/latest/html/documentation/ 236/502
1/6/2019 The same logic can be used to override setProperty or Groovy
getProperty . Documentation
Language
{
name = "Fred"
}
p = ()
"Fred" == p.name
"Flintstone" == p.other
The important thing to note here is that instead of a MetaMethod a MetaProperty instance is looked up. If that exists the
getProperty method of the MetaProperty is called, passing the delegate.
{
invokeMe() { "foo" }
}
"foo" == .invokeMe()
"bar" == .doStuff()
The logic that is used for overriding the static method is the same as we’ve seen before for overriding instance methods. The only
di erence is the access to the metaClass.static property and the call to getStaticMethodName for retrieving the static
MetaMethod instance.
Extending Interfaces
It is possible to add methods onto interfaces with ExpandoMetaClass . To do this however, it must be enabled globally using the
ExpandoMetaClass.enableGlobally() method before application start-up.
list = []
list << 1
list << 2
4 == list.sizeDoubled()
Extension modules
file = (...)
contents = file.getText('utf-8')
The getText method doesn’t exist on the File class. However, Groovy knows it because it is de ned in a special class,
ResourceGroovyMethods :
ResourceGroovyMethods.java
You may notice that the extension method is de ned using a static method in a helper class (where various extension methods
are de ned). The rst argument of the getText method corresponds to the receiver, while additional parameters correspond to
the arguments of the extension method. So here, we are de ning a method called getText on the File class (because the rst
argument is of type File ), which takes a single argument as a parameter (the encoding String ).
Then you have to make the extension module visible to Groovy, which is as simple as having the extension module classes and
descriptor available on classpath. This means that you have the choice:
Instance methods
To add an instance method to an existing class, you need to create an extension class. For example, let’s say you want to add a
maxRetries method on Integer which accepts a closure and executes it at most n times until no exception is thrown. To do
that, you only need to write the following:
MaxRetriesExtension.groovy
http://docs.groovy-lang.org/latest/html/documentation/ 238/502
1/6/2019 Groovy Language Documentation
{ 1
maxRetries( , code) { 2
>= 0
retries =
e =
(retries > 0) {
{
code.call()
} ( err) {
e = err
retries--
}
}
(retries == 0 && e) {
e
}
}
}
Then, after having declared your extension class, you can call it this way:
i=0
5.maxRetries {
i++
}
i == 1
i=0
{
5.maxRetries {
i++
("oops")
}
} ( e) {
i == 5
}
Static methods
It is also possible to add static methods to a class. In that case, the static method needs to be de ned in its own le. Static and
instance extension methods cannot be present in the same class.
StaticStringExtension.groovy
{ 1
greeting( ) { 2
'Hello, world!'
}
}
Module descriptor
For Groovy to be able to load your extension methods, you must declare your extension helper classes. You must create a le
named org.codehaus.groovy.runtime.ExtensionModule into the META-INF/groovy directory:
http://docs.groovy-lang.org/latest/html/documentation/ 239/502
1/6/2019 org.codehaus.groovy.runtime.ExtensionModule Groovy Language Documentation
moduleVersion: the version of your module. Note that version number is only used to check that you don’t load the same
module in two di erent versions.
extensionClasses: the list of extension helper classes for instance methods. You can provide several classes, given that they are
comma separated.
staticExtensionClasses: the list of extension helper classes for static methods. You can provide several classes, given that they
are comma separated.
Note that it is not required for a module to de ne both static helpers and instance helpers, and that you may add several classes
to a single module. You can also extend di erent classes in a single module without problem. It is even possible to use di erent
classes in a single extension class, but it is recommended to group extension methods into classes by feature set.
In this section, we will start with explaining the various compile-time transformations that are bundled with the Groovy
distribution. In a subsequent section, we will describe how you can implement your own AST transformations and what are the
disadvantages of this technique.
global AST transformations are applied transparently, globally, as soon as they are found on compile classpath
local AST transformations are applied by annotating the source code with markers. Unlike global AST transformations, local
AST transformations may support parameters.
Groovy doesn’t ship with any global AST transformation, but you can nd a list of local AST transformations available for you to
use in your code here:
http://docs.groovy-lang.org/latest/html/documentation/ 240/502
1/6/2019 Code generation transformations Groovy Language Documentation
This category of transformation includes AST transformations which help removing boilerplate code. This is typically code that you
have to write but that does not carry any useful information. By autogenerating this boilerplate code, the code you have to write is
left clean and concise and the chance of introducing an error by getting such boilerplate code incorrect is reduced.
@groovy.transform.ToString
The @ToString AST transformation generates a human readable toString representation of the class. For example, annotating
the Person class like below will automatically generate the toString method for you:
groovy.transform.
@ToString
{
firstName
lastName
}
With this de nition, then the following assertion passes, meaning that a toString method taking the eld values from the class
and printing them out has been generated:
The @ToString annotation accepts several parameters which are summarized in the following table:
p = (firstName: 'Jack',
lastName: 'Nicholson')
p.toString() ==
'Person(Nicholson)'
p = (firstName: 'Jack',
lastName: 'Nicholson')
p.toString() ==
'Person(Nicholson)'
http://docs.groovy-lang.org/latest/html/documentation/ 241/502
1/6/2019 Groovy Language Documentation
Attribute Default value Description Example
@ToString(includeSuper= )
{
firstName
lastName
}
p = (id:1, firstName:
'Jack', lastName: 'Nicholson')
p.toString() == 'Person(Jack,
Nicholson, Id(1))'
p = (firstName: 'Jack',
lastName: 'Nicholson')
p.toString() ==
'Person(firstName:Jack,
lastName:Nicholson)'
p = (firstName: 'Jack',
lastName: 'Nicholson')
p.test()
p.toString() == 'Person(Jack,
Nicholson, 42)'
@ToString(includeSuperProperties =
, includeNames = )
{
bandName
}
bono = (name:'Bono',
bandName: 'U2').toString()
bono.toString() ==
'BandMember(bandName:U2, name:Bono)'
http://docs.groovy-lang.org/latest/html/documentation/ 242/502
1/6/2019 Groovy Language Documentation
Attribute Default value Description Example
@ToString(includeSuperFields = ,
includeNames = )
@MapConstructor(includeSuperFields =
)
{
bandName
}
bono = (name:'Bono',
bandName: 'U2').toString()
bono.toString() ==
'BandMember(bandName:U2, name:Bono)'
p = (firstName: 'Jack')
p.toString() == 'Person(Jack)'
p = (firstName: 'Jack',
lastName:'Nicholson')
p.toString() ==
'acme.Person(Jack, Nicholson)'
p = (firstName: 'Jack')
p.toString() ==
'acme.Person(firstName:Jack,
lastName:Nicholson)'
http://docs.groovy-lang.org/latest/html/documentation/ 243/502
1/6/2019 Groovy Language Documentation
Attribute Default value Description Example
p = (firstName: 'Jack',
lastName:'Nicholson')
s1 = p.toString()
s2 = p.toString()
s1 == s2
s1 == 'Person(Jack,
Nicholson)'
s1. (s2) // same instance
p = ($firstName: "Jack")
p.toString() ==
'acme.Person(Jack)'
@groovy.transform.EqualsAndHashCode
The @EqualsAndHashCode AST transformation aims at generating equals and hashCode methods for you. The generated
hashcode follows the best practices as described in E ective Java by Josh Bloch:
groovy.transform.
@EqualsAndHashCode
{
firstName
lastName
}
p1==p2
p1.hashCode() == p2.hashCode()
http://docs.groovy-lang.org/latest/html/documentation/ 244/502
1/6/2019 Groovy Language Documentation
Attribute Default value Description Example
@EqualsAndHashCode(excludes=
['firstName'])
{
firstName
lastName
}
p1 = (firstName: 'Jack',
lastName: 'Nicholson')
p2 = (firstName: 'Bob',
lastName: 'Nicholson')
p1==p2
p1.hashCode() == p2.hashCode()
p1 = (firstName: 'Jack',
lastName: 'Nicholson')
p2 = (firstName: 'Bob',
lastName: 'Nicholson')
p1==p2
p1.hashCode() == p2.hashCode()
http://docs.groovy-lang.org/latest/html/documentation/ 245/502
1/6/2019 Groovy Language Documentation
Attribute Default value Description Example
@Immutable
{
hashCode() {
sleep 100
127
}
}
@EqualsAndHashCode(cache= )
@Immutable
{
slowHashCode =
()
}
p = ()
p.hashCode()
start = .currentTimeMillis()
p.hashCode()
.currentTimeMillis() -
start < 100
@EqualsAndHashCode
{
race
}
@EqualsAndHashCode(callSuper= )
{
firstName
lastName
}
p1 = (race:'Human',
firstName: 'Jack', lastName:
'Nicholson')
p2 = (race: 'Human
beeing', firstName: 'Jack', lastName:
'Nicholson')
p1!=p2
p1.hashCode() != p2.hashCode()
http://docs.groovy-lang.org/latest/html/documentation/ 246/502
1/6/2019 Groovy Language Documentation
Attribute Default value Description Example
( firstName) {
.firstName = firstName
}
}
p1 = ('Jack')
p2 = ('Jack')
p3 = ('Bob')
p1 == p2
p1 != p3
p1 = (first: 'Jack', :
'Smith')
p2 = (first: 'Jack', :
'Spratt')
p3 = (first: 'Bob', :
'Smith')
p1 == p2
p1.hashCode() == p2.hashCode()
p1 != p3
p1.hashCode() != p3.hashCode()
p1 = ($firstName: 'Jack')
p2 = ($firstName: 'Bob')
p1 != p2
p1.hashCode() != p2.hashCode()
@groovy.transform.TupleConstructor
http://docs.groovy-lang.org/latest/html/documentation/ 247/502
1/6/2019 The @TupleConstructor annotation aims at eliminating Groovy
boilerplate code by
Language generating constructors for you. A tuple constructor
Documentation
is created having a parameter for each property (and possibly each eld). Each parameter has a default value (using the initial
value of the property if present or otherwise Java’s default value according to the properties type).
Implementation Details
Normally you don’t need to understand the imp[ementation details of the generated constructor(s); you just use them in the
normal way. However, if you want to add multiple constructors, understand Java integration options or meet requirements of
some dependency injection frameworks, then some details are useful.
As previously mentioned, the generated constructor has default values applied. In later compilation phases, the Groovy compiler’s
standard default value processing behavior is then applied. The end result is that multiple constructors are placed within the
bytecode of your class. This provides a well understood semantics and is also useful for Java integration purposes. As an example,
the following code will generate 3 constructors:
groovy.transform.
@TupleConstructor
{
firstName
lastName
}
The rst constructor is a no-arg constructor which allows the traditional map-style construction so long as you don’t have nal
properties. Groovy calls the no-arg constructor and then the relevant setters under the covers. It is worth noting that if the rst
property (or eld) has type LinkedHashMap or if there is a single Map, AbstractMap or HashMap property (or eld), then the map-
style named arguments won’t be available.
The other constructors are generated by taking the properties in the order they are de ned. Groovy will generate as many
constructors as there are properties (or elds, depending on the options).
Setting the defaults attribute (see the available con guration options table) to false , disables the normal default values
behavior which means:
This attribute is normally only used in situations where another Java framework is expecting exactly one constructor, e.g. injection
frameworks or JUnit parameterized runners.
Immutability support
If the @PropertyOptions annotation is also found on the class with the @TupleConstructor annotation, then the generated
constructor may contain custom property handling logic. The propertyHandler attribute on the @PropertyOptions annotation
could for instance be set to ImmutablePropertyHandler which will result in the addition of the necessary logic for immutable
classes (defensive copy in, cloning, etc.). This normally would happen automatically behind the scenes when you use the
@Immutable meta-annotation. Some of the annotation attributes might not be supported by all property handlers.
Customization options
The @TupleConstructor AST transformation accepts several annotation attributes:
http://docs.groovy-lang.org/latest/html/documentation/ 248/502
1/6/2019 Groovy Language Documentation
Attribute Default Description Example
value
p1 = (firstName: 'Jack',
lastName: 'Nicholson')
p2 = ('Jack')
{
// will fail because the second property
is excluded
p3 = ('Jack', 'Nicholson')
} (e) {
e.message.contains ('Could not find
matching constructor')
}
p1 = (firstName: 'Jack',
lastName: 'Nicholson')
p2 = ('Jack')
{
// will fail because the second property
is not included
p3 = ('Jack', 'Nicholson')
} (e) {
e.message.contains ('Could not find
matching constructor')
}
p1 = (firstName: 'Jack',
lastName: 'Nicholson')
{
p2 = ('Jack', 'Nicholson')
} (e) {
// will fail because properties are not
included
}
http://docs.groovy-lang.org/latest/html/documentation/ 249/502
1/6/2019 Groovy Language Documentation
Attribute Default Description Example
value
p1 = (firstName: 'Jack',
lastName: 'Nicholson', occupation: 'Actor')
p2 = ('Jack', 'Nicholson',
'Actor')
p1.firstName == p2.firstName
p1.lastName == p2.lastName
p1.toString() == 'Jack Nicholson:
Actor'
p1.toString() == p2.toString()
@TupleConstructor(includeSuperProperties= )
{
firstName
lastName
toString() {
"$firstName $lastName: $occupation"
}
}
p1 = (firstName: 'Jack',
lastName: 'Nicholson')
p2 = ('Actor', 'Jack',
'Nicholson')
p1.firstName == p2.firstName
p1.lastName == p2.lastName
p1.toString() == 'Jack Nicholson: null'
p2.toString() == 'Jack Nicholson:
Actor'
http://docs.groovy-lang.org/latest/html/documentation/ 250/502
1/6/2019 Groovy Language Documentation
Attribute Default Description Example
value
@TupleConstructor(includeSuperFields= )
{
firstName
lastName
toString() {
"$firstName $lastName:
${occupation()}"
}
}
p1 = (firstName: 'Jack',
lastName: 'Nicholson', occupation: 'Actor')
p2 = ('Actor', 'Jack',
'Nicholson')
p1.firstName == p2.firstName
p1.lastName == p2.lastName
p1.toString() == 'Jack Nicholson:
Actor'
p2.toString() == p1.toString()
@TupleConstructor(includeSuperProperties =
, callSuper= )
{
firstName
lastName
toString() {
"$firstName $lastName: $occupation"
}
}
p1 = (firstName: 'Jack',
lastName: 'Nicholson')
p2 = ('ACTOR', 'Jack',
'Nicholson')
p1.firstName == p2.firstName
p1.lastName == p2.lastName
p1.toString() == 'Jack Nicholson: null'
p2.toString() == 'Jack Nicholson:
actor'
http://docs.groovy-lang.org/latest/html/documentation/ 251/502
1/6/2019 Groovy Language Documentation
Attribute Default Description Example
value
http://docs.groovy-lang.org/latest/html/documentation/ 252/502
1/6/2019 Groovy Language Documentation
Attribute Default Description Example
value
p = ('Jack')
p.$firstName == 'Jack'
('john', 'smith').name ==
'john smith'
p = ('Jack')
p.first == 'jack'
jack = ('Jack')
shouldFail {
unknown = ()
}
Setting the defaults annotation attribute to false and the force annotation attribute to true allows multiple tuple
constructors to be created by using di erent customization options for the di erent cases (provided each case has a di erent
type signature) as shown in the following example:
http://docs.groovy-lang.org/latest/html/documentation/ 253/502
1/6/2019 Groovy Language Documentation
{
name
}
@groovy.transform.MapConstructor
The @MapConstructor annotation aims at eliminating boilerplate code by generating a map constructor for you. A map
constructor is created such that each property in the class is set based on the value in the supplied map having the key with the
name of the property. Usage is as shown in this example:
groovy.transform.*
@ToString
@MapConstructor
{
firstName
lastName
}
http://docs.groovy-lang.org/latest/html/documentation/ 254/502
1/6/2019 Groovy Language Documentation
( args) {
(args.containsKey('firstName')) {
.firstName = args. ('firstName')
}
(args.containsKey('lastName')) {
.lastName = args. ('lastName')
}
}
@groovy.transform.Canonical
The @Canonical meta-annotation combines the @ToString, @EqualsAndHashCode and @TupleConstructor annotations:
groovy.transform.
@Canonical
{
firstName
lastName
}
p1 = (firstName: 'Jack', lastName: 'Nicholson')
p1.toString() == 'Person(Jack, Nicholson)' // Effect of @ToString
A similar immutable class can be generated using the @Immutable meta-annotation instead. The @Canonical meta-annotation
supports the con guration options found in the annotations it aggregates. See those annotations for more details.
groovy.transform.
@Canonical(excludes=['lastName'])
{
firstName
lastName
}
p1 = (firstName: 'Jack', lastName: 'Nicholson')
p1.toString() == 'Person(Jack)' // Effect of @ToString(excludes=['lastName'])
The @Canonical meta-annotation can be used in conjunction with an explicit use one or more of its component annotations, like
this:
http://docs.groovy-lang.org/latest/html/documentation/ 255/502
1/6/2019 Groovy Language Documentation
groovy.transform.
@Canonical(excludes=['lastName'])
{
firstName
lastName
}
p1 = (firstName: 'Jack', lastName: 'Nicholson')
p1.toString() == 'Person(Jack)' // Effect of @ToString(excludes=['lastName'])
Any applicable annotation attributes from @Canonical are passed along to the explicit annotation but attributes already existing
in the explicit annotation take precedence.
@groovy.transform.InheritConstructors
The @InheritConstructor AST transformation aims at generating constructors matching super constructors for you. This is in
particular useful when overriding exception classes:
groovy.transform.
@InheritConstructors
{}
// Java 7 only
// new CustomException("A custom message", new RuntimeException(), false, true)
The @InheritConstructor AST transformation supports the following con guration options:
@InheritConstructors(constructorAnnotations= )
{}
.constructors[0].annotations[0].annotationType().name
== 'groovy.transform.Generated'
.constructors[0].annotations[1].annotationType().name
== 'ConsAnno'
http://docs.groovy-lang.org/latest/html/documentation/ 256/502
1/6/2019 Groovy Language Documentation
Attribute Default Description Example
value
.constructors[0].parameterAnnotations[0]
[0].annotationType().name == 'ParamAnno'
@groovy.lang.Category
The @Category AST transformation simpli es the creation of Groovy categories. Historically, a Groovy category was written like
this:
{
triple( ) {
3*
}
}
( ) {
9 == 3.triple()
}
The @Category transformation lets you write the same using an instance-style class, rather than a static class style. This removes
the need for having the rst argument of each method being the receiver. The category can be written like this:
@Category( )
{
triple() { 3* }
}
( ) {
9 == 3.triple()
}
Note that the mixed in class can be referenced using this instead. It’s also worth noting that using instance elds in a category
class is inherently unsafe: categories are not stateful (like traits).
@groovy.transform.IndexedProperty
The @IndexedProperty annotation aims at generating indexed getters/setters for properties of list/array types. This is in
particular useful if you want to use a Groovy class from Java. While Groovy supports GPath to access properties, this is not
available from Java. The @IndexedProperty annotation will generate indexed properties of the following form:
{
@IndexedProperty [] someArray = [2]
@IndexedProperty someList = []
}
bean = ()
bean.setSomeArray(0, 'value')
bean.setSomeList(0, 123)
bean.someArray[0] == 'value'
bean.someList == [123]
@groovy.lang.Lazy
http://docs.groovy-lang.org/latest/html/documentation/ 257/502
1/6/2019 The @Lazy AST transformation implements lazy initialization of Language
Groovy elds. For example, the following code:
Documentation
{
@Lazy myField
}
$myField
getMyField() {
($myField!= ) { $myField }
{
$myField = ()
$myField
}
}
The default value which is used to initialize the eld is the default constructor of the declaration type. It is possible to de ne a
default value by using a closure on the right hand side of the property assignment, as in the following example:
class SomeBean {
@Lazy LinkedList myField = { ['a','b','c']}()
}
List $myField
List getMyField() {
if ($myField!=null) { return $myField }
else {
$myField = { ['a','b','c']}()
return $myField
}
}
If the eld is declared volatile then initialization will be synchronized using the double-checked locking
(http://en.wikipedia.org/wiki/Double-checked_locking) pattern.
Using the soft=true parameter, the helper eld will use a SoftReference instead, providing a simple way to implement
caching. In that case, if the garbage collector decides to collect the reference, initialization will occur the next time the eld is
accessed.
@groovy.lang.Newify
The @Newify AST transformation is used to bring alternative syntaxes to construct objects:
@Newify([Tree,Leaf])
class TreeBuilder {
Tree tree = Tree(Leaf('A'),Leaf('B'),Tree(Leaf('C')))
}
@Newify([Tree,Leaf])
class TreeBuilder {
Tree tree = Tree.new(Leaf.new('A'),Leaf.new('B'),Tree.new(Leaf.new('C')))
}
@groovy.transform.Sortable
http://docs.groovy-lang.org/latest/html/documentation/ 258/502
1/6/2019 The @Sortable AST transformation is used to help write Groovy
classes Language
that are Comparable and easily sorted typically by numerous
Documentation
properties. It is easy to use as shown in the following example where we annotate the Person class:
groovy.transform.
@Sortable {
first
born
}
it contains a compareTo method with an implementation based on the natural ordering of the first , last and born
properties
compareTo(java.lang. obj) {
( . (obj)) {
0
}
(!(obj )) {
-1
}
java.lang. value = .first <=> obj.first
(value != 0) {
value
}
value = . <=> obj.
(value != 0) {
value
}
value = .born <=> obj.born
(value != 0) {
value
}
0
}
As an example of the generated comparators, the comparatorByFirst comparator will have a compare method that looks like
this:
The Person class can be used wherever a Comparable is expected and the generated comparators wherever a Comparator is
expected as shown by these examples:
http://docs.groovy-lang.org/latest/html/documentation/ 259/502
1/6/2019 Groovy Language Documentation
people = [
(first: 'Johnny', : 'Depp', born: 1963),
(first: 'Keira', : 'Knightley', born: 1985),
(first: 'Geoffrey', : 'Rush', born: 1951),
(first: 'Orlando', : 'Bloom', born: 1977)
]
Normally, all properties are used in the generated compareTo method in the priority order in which they are de ned. You can
include or exclude certain properties from the generated compareTo method by giving a list of property names in the includes
or excludes annotation attributes. If using includes , the order of the property names given will determine the priority of
properties when comparing. To illustrate, consider the following Person class de nition:
@Sortable(includes='first,born') {
born
first
}
It will have two comparator methods comparatorByFirst and comparatorByBorn and the generated compareTo method will
look like this:
compareTo(java.lang. obj) {
( . (obj)) {
0
}
(!(obj )) {
-1
}
java.lang. value = .first <=> obj.first
(value != 0) {
value
}
value = .born <=> obj.born
(value != 0) {
value
}
0
}
people = [
(first: 'Ben', : 'Affleck', born: 1972),
(first: 'Ben', : 'Stiller', born: 1965)
]
The behavior of the @Sortable AST transformation can be further changed using the following additional parameters:
http://docs.groovy-lang.org/latest/html/documentation/ 260/502
1/6/2019 Groovy Language Documentation
Attribute Default value Description Example
finalists = [
('Serena'),
('Venus'),
('CoCo'),
('Mirjana')
]
finalists.sort()*.name ==
['CoCo', 'Venus', 'Serena',
'Mirjana']
finalists = [
('USA', 'Serena'),
('USA', 'Venus'),
('USA', 'CoCo'),
('Croatian', 'Mirjana')
]
finalists.sort()*.name ==
['Mirjana', 'CoCo', 'Serena',
'Venus']
http://docs.groovy-lang.org/latest/html/documentation/ 261/502
1/6/2019 Groovy Language Documentation
Attribute Default value Description Example
@Canonical(includeSuperProperties =
)
@Sortable(includeSuperProperties =
)
{
country
}
people = [
('Bob', 'Italy'),
('Cathy', 'Hungary'),
('Cathy', 'Egypt'),
('Bob', 'Germany'),
('Alan', 'France')
]
people.sort()*.name ==
['Alan', 'Bob', 'Bob', 'Cathy',
'Cathy']
people.sort()*.country ==
['France', 'Germany', 'Italy',
'Egypt', 'Hungary']
@groovy.transform.builder.Builder
The @Builder AST transformation is used to help write classes that can be created using uent api calls. The transform supports
multiple building strategies to cover a range of cases and there are a number of con guration options to customize the building
process. If you’re an AST hacker, you can also de ne your own strategy class. The following table lists the available strategies that
are bundled with Groovy and the con guration options each strategy supports.
DefaultStrategy creates a yes, default yes, default "builder" yes, default "build" yes, yes
nested <TypeName>Builder default
helper ""
class
InitializerStrategy creates a yes, default yes, default yes, default yes, yes
nested <TypeName>Initializer "createInitializer" "create" but default
helper usually only used ""
class internally
providing
type-safe
uent
creation
SimpleStrategy
http://docs.groovy-lang.org/latest/html/documentation/ 262/502
1/6/2019 To use the SimpleStrategy , annotate your Groovy classGroovy
using the @Builder
Language annotation, and specify the strategy as shown in
Documentation
this example:
groovy.transform.builder.*
@Builder(builderStrategy= )
{
first
born
}
p1 = ().setFirst('Johnny').setLast('Depp').setBorn(1963)
"$p1.first $p1.last" == 'Johnny Depp'
For each property, a generated setter will be created which looks like this:
setFirst(java.lang. first) {
.first = first
groovy.transform.builder.*
@Builder(builderStrategy= , prefix="")
{
first
born
}
p = ().first('Johnny'). ('Depp').born(1963)
"$p.first $p.last" == 'Johnny Depp'
You can use the SimpleStrategy in conjunction with @TupleConstructor . If your @Builder annotation doesn’t have explicit
includes or excludes annotation attributes but your @TupleConstructor annotation does, the ones from
@TupleConstructor will be re-used for @Builder . The same applies for any annotation aliases which combine
@TupleConstructor such as @Canonical .
The annotation attribute useSetters can be used if you have a setter which you want called as part of the construction process.
See the JavaDoc for details.
Groovy already has built-in building mechanisms. Don’t rush to using @Builder if the built-in mechanisms meet
your needs. Some examples:
{
first
born
}
groovy.transform.builder.*
@Builder(builderStrategy= , forClass= )
{ }
p = ().first('Johnny'). ('Depp').born(1963).build()
"$p.first $p.last" == 'Johnny Depp'
Note that the (normally empty) builder class you provide will be lled in with appropriate setters and a build method. The
generated build method will look something like:
build() {
_thePerson = ()
_thePerson.first = first
_thePerson. =
_thePerson.born = born
_thePerson
}
The class you are creating the builder for can be any Java or Groovy class following the normal JavaBean conventions, e.g. a no-arg
constructor and setters for the properties. Here is an example using a Java class:
groovy.transform.builder.*
@Builder(builderStrategy= , forClass=javax.swing. )
{}
model =
().enabled( ).pressed( ).armed( ).rollover( ).selected( ).build()
model.isArmed()
model.isPressed()
model.isEnabled()
model.isSelected()
model.isRollover()
The generated builder can be customised using the prefix , includes , excludes and buildMethodName annotation
attributes. Here is an example illustrating various customisations:
http://docs.groovy-lang.org/latest/html/documentation/ 264/502
1/6/2019 Groovy Language Documentation
groovy.transform.builder.*
groovy.transform.
@Canonical
{
first
born
}
p = ().withFirst('Johnny').withLast('Depp').create()
"$p.first $p.last" == 'Johnny Depp'
The builderMethodName and builderClassName annotation attributes for @Builder aren’t applicable for this strategy.
You can use the ExternalStrategy in conjunction with @TupleConstructor . If your @Builder annotation doesn’t have explicit
includes or excludes annotation attributes but the @TupleConstructor annotation of the class you are creating the builder
for does, the ones from @TupleConstructor will be re-used for @Builder . The same applies for any annotation aliases which
combine @TupleConstructor such as @Canonical .
DefaultStrategy
To use the DefaultStrategy , annotate your Groovy class using the @Builder annotation as shown in this example:
groovy.transform.builder.
@Builder
{
firstName
lastName
age
}
person = .builder().firstName("Robert").lastName("Lewandowski").age(21).build()
person.firstName == "Robert"
person.lastName == "Lewandowski"
person.age == 21
If you want, you can customize various aspects of the building process using the builderClassName , buildMethodName ,
builderMethodName , prefix , includes and excludes annotation attributes, some of which are used in the example here:
groovy.transform.builder.
p = .maker().withFirstName("Robert").withLastName("Lewandowski").make()
"$p.firstName $p.lastName" == "Robert Lewandowski"
This strategy also supports annotating static methods and constructors. In this case, the static method or constructor parameters
become the properties to use for building purposes and in the case of static methods, the return type of the method becomes the
target class being built. If you have more than one @Builder annotation used within a class (at either the class, method or
constructor positions) then it is up to you to ensure that the generated helper classes and factory methods have unique names
(i.e. no more than one can use the default name values). Here is an example highlighting method and constructor usage (and also
illustrating the renaming required for unique names).
http://docs.groovy-lang.org/latest/html/documentation/ 265/502
1/6/2019 Groovy Language Documentation
groovy.transform.builder.*
groovy.transform.*
@ToString
@Builder
{
first,
born
(){}
@Builder(builderClassName='MovieBuilder', builderMethodName='byRoleBuilder')
( roleName) {
(roleName == 'Jack Sparrow') {
.first = 'Johnny'; . = 'Depp'; .born = 1963
}
}
@Builder(builderClassName='SplitBuilder', builderMethodName='splitBuilder')
split( name, year) {
parts = name.split(' ')
(first: parts[0], : parts[1], born: year)
}
}
InitializerStrategy
To use the InitializerStrategy , annotate your Groovy class using the @Builder annotation, and specify the strategy as
shown in this example:
groovy.transform.builder.*
groovy.transform.*
@ToString
@Builder(builderStrategy= )
{
firstName
lastName
age
}
Your class will be locked down to have a single public constructor taking a "fully set" initializer. It will also have a factory method to
create the initializer. These are used as follows:
http://docs.groovy-lang.org/latest/html/documentation/ 266/502
1/6/2019 Groovy Language Documentation
@CompileStatic
firstLastAge() {
( .createInitializer().firstName("John").lastName("Smith").age(21)).toString() ==
'Person(John, Smith, 21)'
}
firstLastAge()
Any attempt to use the initializer which doesn’t involve setting all the properties (though order is not important) will result in a
compilation error. If you don’t need this level of strictness, you don’t need to use @CompileStatic .
You can use the InitializerStrategy in conjunction with @Canonical and @Immutable . If your @Builder annotation doesn’t
have explicit includes or excludes annotation attributes but your @Canonical annotation does, the ones from @Canonical
will be re-used for @Builder . Here is an example using @Builder with @Immutable :
groovy.transform.builder.*
groovy.transform.*
groovy.transform.options. .PRIVATE
@Builder(builderStrategy= )
@Immutable
@VisibilityOptions(PRIVATE)
{
first
born
}
publicCons = .constructors
publicCons.size() == 1
@CompileStatic
createFirstLastBorn() {
p = ( .createInitializer().first('Johnny'). ('Depp').born(1963))
"$p.first $p.last $p.born" == 'Johnny Depp 1963'
}
createFirstLastBorn()
The annotation attribute useSetters can be used if you have a setter which you want called as part of the construction process.
See the JavaDoc for details.
This strategy also supports annotating static methods and constructors. In this case, the static method or constructor parameters
become the properties to use for building purposes and in the case of static methods, the return type of the method becomes the
target class being built. If you have more than one @Builder annotation used within a class (at either the class, method or
constructor positions) then it is up to you to ensure that the generated helper classes and factory methods have unique names
(i.e. no more than one can use the default name values). For an example of method and constructor usage but using the
DefaultStrategy strategy, consult that strategy’s documentation.
@groovy.transform.AutoImplement
The @AutoImplement AST transformation supplies dummy implementations for any found abstract methods from superclasses
or interfaces. The dummy implementation is the same for all abstract methods found and can be:
essentially empty (exactly true for void methods and for methods with a return type, returns the default value for that type)
The rst example illustrates the default case. Our class is annotated with @AutoImplement , has a superclass and a single
interface as can be seen here:
http://docs.groovy-lang.org/latest/html/documentation/ 267/502
1/6/2019 Groovy Language Documentation
groovy.transform.
@AutoImplement
< > { }
A void close() method from the Closeable interface is supplied and left empty. Implementations are also supplied for the
three abstract methods from the super class. The get , addAll and size methods have return types of String , boolean and
int respectively with default values null , false and 0 . We can use our class (and check the expected return type for one of
the methods) using the following code:
().size() == 0
< > {
( param0) {
close() {
}
size() {
0
}
The second example illustrates the simplest exception case. Our class is annotated with @AutoImplement , has a superclass and
an annotation attribute indicates that an IOException should be thrown if any of our "dummy" methods are called. Here is the
class de nition:
@AutoImplement(exception= )
{ }
We can use the class (and check the expected exception is thrown for one of the methods) using the following code:
groovy.test. .shouldFail
shouldFail( ) {
().flush()
}
It is also worthwhile examining the equivalent generated code where three void methods have been provided all of which throw
the supplied exception:
http://docs.groovy-lang.org/latest/html/documentation/ 268/502
1/6/2019 Groovy Language Documentation
{
flush() {
()
}
close() {
()
}
The third example illustrates the exception case with a supplied message. Our class is annotated with @AutoImplement ,
implements an interface, and has annotation attributes to indicate that an UnsupportedOperationException with
Not supported by MyIterator as the message should be thrown for any supplied methods. Here is the class de nition:
We can use the class (and check the expected exception is thrown and has the correct message for one of the methods) using the
following code:
ex = shouldFail( ) {
().hasNext()
}
ex.message == 'Not supported by MyIterator'
It is also worthwhile examining the equivalent generated code where three void methods have been provided all of which throw
the supplied exception:
< > {
hasNext() {
('Not supported by MyIterator')
}
() {
('Not supported by MyIterator')
}
The fourth example illustrates the case of user supplied code. Our class is annotated with @AutoImplement , implements an
interface, has an explcitly overriden hasNext method, and has an annotation attribute containing the supplied code for any
supplied methods. Here is the class de nition:
We can use the class (and check the expected exception is thrown and has a message of the expected form) using the following
code:
http://docs.groovy-lang.org/latest/html/documentation/ 269/502
1/6/2019 Groovy Language Documentation
ex = shouldFail( ) {
(). ()
}
ex.message.startsWith('Should never be called but was called on ')
It is also worthwhile examining the equivalent generated code where the next method has been supplied:
hasNext() {
() {
('Should never be called but was called on ' +
())
}
@groovy.transform.BaseScript
@BaseScript is used within scripts to indicate that the script should extend fron a custom script base class rather than
groovy.lang.Script . See the documentation for domain speci c languages for further details.
@groovy.lang.Delegate
The @Delegate AST transformation aims at implementing the delegation design pattern. In the following class:
{
@Delegate
title
}
The when property is annotated with @Delegate , meaning that the Event class will delegate calls to Date methods to the
when property. In this case, the generated code looks like this:
title
before( other) {
.before(other)
}
// ...
}
Then you can call the before method, for example, directly on the Event class:
Instead of annotating a property (or eld), you can also annotate a method. In this case, the method can be thought of as a getter
or factory method for the delegate. As an example, here is a class which (rather unusually) has a pool of delegates which are
accessed in a round-robin fashion:
http://docs.groovy-lang.org/latest/html/documentation/ 270/502
1/6/2019 Groovy Language Documentation
{
robinCount = 0
< > items = [[0], [1], [2]]
@Delegate
getRoundRobinList() {
items[robinCount++ % items.size()]
}
t = ()
t << 'fee'
t << 'fi'
t << 'fo'
t << 'fum'
t.checkItems([[0, 'fee', 'fum'], [1, 'fi'], [2, 'fo']])
Using a standard list in this round-robin fashion would violate many expected properties of lists, so don’t expect the above class to
do anything useful beyond this trivial example.
The behavior of the @Delegate AST transformation can be changed using the following parameters:
http://docs.groovy-lang.org/latest/html/documentation/ 271/502
1/6/2019 Groovy Language Documentation
Attribute Default Description Example
value
http://docs.groovy-lang.org/latest/html/documentation/ 272/502
1/6/2019 Groovy Language Documentation
Attribute Default Description Example
value
@groovy.transform.Immutable
The @Immutable meta-annotation combines the following annotations:
@ToString
@EqualsAndHashCode
@TupleConstructor
@MapConstructor
@ImmutableBase
http://docs.groovy-lang.org/latest/html/documentation/ 273/502
1/6/2019 @ImmutableOptions Groovy Language Documentation
@PropertyOptions
@KnownImmutable
The @Immutable meta-annotation simpli es the creation of immutable classes. Immutable classes are useful since they are often
easier to reason about and are inherently thread-safe. See E ective Java, Minimize Mutability
(http://www.informit.com/store/e ective-java-9780134685991) for all the details about how to achieve immutable classes in Java.
The @Immutable meta-annotation does most of the things described in E ective Java for you automatically. To use the meta-
annotation, all you have to do is annotate the class like in the following example:
groovy.transform.
@Immutable
{
x
y
}
One of the requirements for immutable classes is that there is no way to modify any state information within the class. One
requirement to achieve this is to use immutable classes for each property or alternatively perform special coding such as
defensive copy in and defensive copy out for any mutable properties within the constructors and property getters. Between
@ImmutableBase , @MapConstructor and @TupleConstructor properties are either identi ed as immutable or the special
coding for numerous known cases is handled automatically. Various mechanisms are provided for you to extend the handled
property types which are allowed. See @ImmutableOptions and @KnownImmutable for details.
The results of applying @Immutable to a class are pretty similar to those of applying the @Canonical meta-annotation but the
generated class will have extra logic to handle immutability. You will observe this by, for instance, trying to modify a property
which will result in a ReadOnlyPropertyException being thrown since the backing eld for the property will have been
automatically made nal.
The @Immutable meta-annotation supports the con guration options found in the annotations it aggregates. See those
annotations for more details.
@groovy.transform.ImmutableBase
Immutable classes generated with @ImmutableBase are automatically made nal. Also, the type of each property is checked and
various checks are made on the class, for example, public instance elds currently aren’t allowed. It also generates a copyWith
constructor if desired.
@Immutable( copyWith= )
{
name
age
}
bob = ( 'bob', 43 )
alice = bob.copyWith( name:'alice'
)
alice.name == 'alice'
alice.age == 43
@groovy.transform.PropertyOptions
This annotation allows you to specify a custom property handler to be used by transformations during class construction. It is
ignored by the main Groovy compiler but is referenced by other transformations like @TupleConstructor , @MapConstructor ,
and @ImmutableBase . It is frequently used behind the scenes by the @Immutable meta-annotation.
http://docs.groovy-lang.org/latest/html/documentation/ 274/502
1/6/2019 @groovy.transform.VisibilityOptions Groovy Language Documentation
This annotation allows you to specify a custom visibility for a construct generated by another transformation. It is ignored by the
main Groovy compiler but is referenced by other transformations like @TupleConstructor , @MapConstructor , and
@NamedVariant .
@groovy.transform.ImmutableOptions
Groovy’s immutability support relies on a prede ned list of known immutable classes (like java.net.URI or java.lang.String
and fails if you use a type which is not in that list, you are allowed to add to the list of known immutable types thanks to the
following annotation attributes of the @ImmutableOptions annotation:
groovy.transform.
@TupleConstructor
{
x
y
toString() { "
($x,$y)" }
}
@Immutable(knownImmutableClasses=
[ ])
{
a,b,c
}
@TupleConstructor
{
x
y
toString() { "
($x,$y)" }
}
@Immutable(knownImmutables=
['a','b','c'])
{
a,b,c
}
If you deem a type as immutable and it isn’t one of the ones automatically handled, then it is up to you to correctly code that class
to ensure immutability.
@groovy.transform.KnownImmutable
The @KnownImmutable annotation isn’t actually one that triggers any AST transformations. It is simply a marker annotation. You
can annotate your classes with the annotation (including Java classes) and they will be recognized as acceptable types for
members within an immutable class. This saves you having to explicitly use the knownImmutables or knownImmutableClasses
annotation attributes from @ImmutableOptions .
@groovy.transform.Memoized
The @Memoized AST transformations simpli es the implementation of caching by allowing the result of method calls to be cached
just by annotating the method with @Memoized . Let’s imagine the following method:
http://docs.groovy-lang.org/latest/html/documentation/ 275/502
1/6/2019 Groovy Language Documentation
longComputation( seed) {
// slow computation
.sleep(100*seed)
.nanoTime()
}
This emulates a long computation, based on the actual parameters of the method. Without @Memoized , each method call would
take several seconds plus it would return a random result:
x = longComputation(1)
y = longComputation(1)
x!=y
Adding @Memoized changes the semantics of the method by adding caching, based on the parameters:
@Memoized
longComputation( seed) {
// slow computation
.sleep(100*seed)
.nanoTime()
}
The size of the cache can be con gured using two optional parameters:
protectedCacheSize: the number of results which are guaranteed not to be cleared after garbage collection
By default, the size of the cache is unlimited and no cache result is protected from garbage collection. Setting a
protectedCacheSize>0 would create an unlimited cache with some results protected. Setting maxCacheSize>0 would create a
limited cache but without any protection from garbage protection. Setting both would create a limited, protected cache.
@groovy.transform.TailRecursive
The @TailRecursive annotation can be used to automatically transform a recursive call at the end of a method into an
equivalent iterative version of the same code. This avoids stack over ow due to too many recursive calls. Below is an example of
use when calculating factorial:
groovy.transform.
groovy.transform.
@CompileStatic
{
@TailRecursive
factorial( i, product = 1) {
( i == 1) {
product
}
factorial(i-1, product*i)
}
}
.factorial(1) == 1
.factorial(3) == 6
.factorial(5) == 120
.factorial(50000).toString().size() == 213237 // Big number and no Stack Overflow
http://docs.groovy-lang.org/latest/html/documentation/ 276/502
1/6/2019 Currently, the annotation will only work for self-recursive Groovy
methodLanguage
calls, i.e. aDocumentation
single recursive call to the exact same method again.
Consider using Closures and trampoline() if you have a scenario involving simple mutual recursion. Also note that only non-
void methods are currently handled (void calls will result in a compilation error).
Currently, some forms of method overloading can trick the compiler, and some non-tail recursive calls are
erroneously treated as tail recursive.
@groovy.lang.Singleton
The @Singleton annotation can be used to implement the singleton design pattern on a class. The singleton instance is de ned
eagerly by default, using class initialization, or lazily, in which case the eld is initialized using double checked locking.
@Singleton
{
greeting( name) { "Hello, $name!" }
}
.instance.greeting('Bob') == 'Hello, Bob!'
By default, the singleton is created eagerly when the class is initialized and available through the instance property. It is possible
to change the name of the singleton using the property parameter:
@Singleton( ='theOne')
{
greeting( name) { "Hello, $name!" }
}
And it is also possible to make initialization lazy using the lazy parameter:
{
init =
}
@Singleton(lazy= ,strict= )
{
init() {}
() {
.init =
}
greeting( name) { "Hello, $name!" }
}
.init() // make sure class is initialized
.init ==
.instance
.init ==
.instance.greeting('Bob') == 'Hello, Bob!'
In this example, we also set the strict parameter to false, which allows us to de ne our own constructor.
@groovy.lang.Mixin
Deprecated. Consider using traits instead.
Logging improvements
Groovy provides AST transformation that helps integrating with the most widely used logging frameworks. It’s worth noting that
annotating a class with one of those annotations doesn’t prevent you from adding the appropriate logging framework on
classpath.
wrap all calls to log.level() into the appropriate log.isLevelEnabled guard, depending on the underlying framework
category (defaults to the class name) is the name of the logger category
@groovy.util.logging.Log
The rst logging AST transformation available is the @Log annotation which relies on the JDK logging framework. Writing:
@groovy.util.logging.
{
greet() {
log.info 'Called greeter'
println 'Hello, world!'
}
}
is equivalent to writing:
java.util.logging.
java.util.logging.
{
log = .getLogger( .name)
greet() {
(log.isLoggable( .INFO)) {
log.info 'Called greeter'
}
println 'Hello, world!'
}
}
@groovy.util.logging.Commons
Groovy supports the Apache Commons Logging (http://commons.apache.org/proper/commons-logging/) framework using to the
@Commons annotation. Writing:
@groovy.util.logging.
{
greet() {
log.debug 'Called greeter'
println 'Hello, world!'
}
}
is equivalent to writing:
org.apache.commons.logging.
org.apache.commons.logging.
{
log = .getLog( )
greet() {
(log.isDebugEnabled()) {
log.debug 'Called greeter'
}
println 'Hello, world!'
}
}
@groovy.util.logging.Log4j
Groovy supports the Apache Log4j 1.x (http://logging.apache.org/log4j/1.2/) framework using to the @Log4j annotation. Writing:
http://docs.groovy-lang.org/latest/html/documentation/ 278/502
1/6/2019 Groovy Language Documentation
@groovy.util.logging.
{
greet() {
log.debug 'Called greeter'
println 'Hello, world!'
}
}
is equivalent to writing:
org.apache.log4j.
{
log = .getLogger( )
greet() {
(log.isDebugEnabled()) {
log.debug 'Called greeter'
}
println 'Hello, world!'
}
}
@groovy.util.logging.Log4j2
Groovy supports the Apache Log4j 2.x (http://logging.apache.org/log4j/2.x/) framework using to the @Log4j2 annotation. Writing:
@groovy.util.logging.
{
greet() {
log.debug 'Called greeter'
println 'Hello, world!'
}
}
is equivalent to writing:
org.apache.logging.log4j.
org.apache.logging.log4j.
{
log = .getLogger( )
greet() {
(log.isDebugEnabled()) {
log.debug 'Called greeter'
}
println 'Hello, world!'
}
}
@groovy.util.logging.Slf4j
Groovy supports the Simple Logging Facade for Java (SLF4J) (http://www.slf4j.org/) framework using to the @Slf4j annotation.
Writing:
@groovy.util.logging.
{
greet() {
log.debug 'Called greeter'
println 'Hello, world!'
}
}
is equivalent to writing:
http://docs.groovy-lang.org/latest/html/documentation/ 279/502
1/6/2019 Groovy Language Documentation
org.slf4j.
org.slf4j.
{
log = .getLogger( )
greet() {
(log.isDebugEnabled()) {
log.debug 'Called greeter'
}
println 'Hello, world!'
}
}
Declarative concurrency
The Groovy language provides a set of annotations aimed at simplifying common concurrency patterns in a declarative approach.
@groovy.transform.Synchronized
The @Synchronized AST transformations works in a similar way to the synchronized keyword but locks on di erent objects for
safer concurrency. It can be applied on any method or static method:
groovy.transform.
java.util.concurrent.
java.util.concurrent.
{
cpt
@Synchronized
incrementAndGet() {
cpt++
}
() {
cpt
}
}
Writing this is equivalent to creating a lock object and wrapping the whole method into a synchronized block:
{
cpt
$lock = ()
incrementAndGet() {
($lock) {
cpt++
}
}
() {
cpt
}
By default, @Synchronized creates a eld named $lock (or $LOCK for a static method) but you can make it use any eld you
want by specifying the value attribute, like in the following example:
http://docs.groovy-lang.org/latest/html/documentation/ 280/502
1/6/2019 Groovy Language Documentation
groovy.transform.
java.util.concurrent.
java.util.concurrent.
{
cpt
myLock = ()
@Synchronized('myLock')
incrementAndGet() {
cpt++
}
() {
cpt
}
}
groovy.transform.
groovy.transform.
{
< , > map = [:].withDefault { 0 }
@WithReadLock
( id) {
map. (id)
}
@WithWriteLock
add( id, num) {
.sleep(200) // emulate long computation
map.put(id, map. (id)+num)
}
}
is equivalent to this:
http://docs.groovy-lang.org/latest/html/documentation/ 281/502
1/6/2019 Groovy Language Documentation
groovy.transform.
groovy.transform.
(java.lang. id) {
$reentrantlock.readLock(). ()
{
map. (id)
}
{
$reentrantlock.readLock().unlock()
}
}
Both @WithReadLock and @WithWriteLock support specifying an alternative lock object. In that case, the referenced eld must
be declared by the user, like in the following alternative:
groovy.transform.
groovy.transform.
java.util.concurrent.locks.
{
< , > map = [:].withDefault { 0 }
customLock = ()
@WithReadLock('customLock')
( id) {
map. (id)
}
@WithWriteLock('customLock')
add( id, num) {
.sleep(200) // emulate long computation
map.put(id, map. (id)+num)
}
}
For details
the default AutoCloneStyle.CLONE strategy calls super.clone() rst then clone() on each cloneable property
the AutoCloneStyle.SIMPLE strategy uses a regular constructor call and copies properties from the source to the clone
the AutoCloneStyle.SERIALIZATION strategy uses serialization (or externalization) to clone the object
Each of those strategies have pros and cons which are discussed in the Javadoc for groovy.transform.AutoClone
(http://docs.groovy-lang.org/2.5.5/html/gapi/index.html?groovy/transform/AutoClone.html) and groovy.transform.AutoCloneStyle
(http://docs.groovy-lang.org/2.5.5/html/gapi/index.html?groovy/transform/AutoCloneStyle.html) .
groovy.transform.
@AutoClone
{
isbn
title
< > authors
publicationDate
}
is equivalent to this:
{
isbn
title
< > authors
publicationDate
clone() {
result = .clone()
result.authors = authors ? ( ) authors.clone() : authors
result.publicationDate = publicationDate.clone()
result
}
}
Note that the String properties aren’t explicitly handled because Strings are immutable and the clone() method from Object
will copy the String references. The same would apply to primitive elds and most of the concrete subclasses of
java.lang.Number .
http://docs.groovy-lang.org/latest/html/documentation/ 283/502
1/6/2019 Groovy Language Documentation
Attribute Default Description Example
value
@AutoClone(style= .SIMPLE,includeFields=
{
isbn
title
authors
publicationDate
}
@groovy.transform.AutoExternalize
The @AutoExternalize AST transformation will assist in the creation of java.io.Externalizable classes. It will automatically
add the interface to the class and generate the writeExternal and readExternal methods. For example, this code:
groovy.transform.
@AutoExternalize
{
isbn
title
price
}
java.io. {
isbn
title
price
writeExternal( ) {
.writeObject(isbn)
.writeObject(title)
.writeFloat( price )
}
readExternal( oin) {
isbn = ( ) oin.readObject()
title = ( ) oin.readObject()
price = oin.readFloat()
}
The @AutoExternalize annotation supports two parameters which will let you slightly customize its behavior:
http://docs.groovy-lang.org/latest/html/documentation/ 284/502
1/6/2019 Groovy Language Documentation
Attribute Default Description Example
value
@AutoExternalize(includeFields= )
{
isbn
title
price
}
Safer scripting
The Groovy language makes it easy to execute user scripts at runtime (for example using groovy.lang.GroovyShell
(http://docs.groovy-lang.org/2.5.5/html/gapi/index.html?groovy/lang/GroovyShell.html)), but how do you make sure that a script
won’t eat all CPU (in nite loops) or that concurrent scripts won’t slowly consume all available threads of a thread pool? Groovy
provides several annotations which are aimed towards safer scripting, generating code which will for example allow you to
interrupt execution automatically.
@groovy.transform.ThreadInterrupt
One complicated situation in the JVM world is when a thread can’t be stopped. The Thread#stop method exists but is deprecated
(and isn’t reliable) so your only chance relies in Thread#interrupt . Calling the latter will set the interrupt ag on the thread,
but it will not stop the execution of the thread. This is problematic because it’s the responsibility of the code executing in the
thread to check the interrupt ag and properly exit. This makes sense when you, as a developer, know that the code you are
executing is meant to be run in an independent thread, but in general, you don’t know it. It’s even worse with user scripts, who
might not even know what a thread is (think of DSLs).
@ThreadInterrupt simpli es this by adding thread interruption checks at critical places in the code:
( ) {
i++
}
This is an obvious in nite loop. If this code executes in its own thread, interrupting wouldn’t help: if you join on the thread, then
the calling code would be able to continue, but the thread would still be alive, running in background without any ability for you to
stop it, slowly causing thread starvation.
One possibility to work around this is to set up your shell this way:
http://docs.groovy-lang.org/latest/html/documentation/ 285/502
1/6/2019 Groovy Language Documentation
config = ()
config.addCompilationCustomizers(
( )
)
binding = (i:0)
shell = (binding,config)
The shell is then con gured to automatically apply the @ThreadInterrupt AST transformations on all scripts. This allows you to
execute user scripts this way:
t = .start {
shell.evaluate(userCode)
}
t.join(1000) // give at most 1000ms for the script to complete
(t.alive) {
t.interrupt()
}
( ) {
( .currentThread().interrupted) {
('The current thread has been interrupted.')
}
i++
}
The check which is introduced inside the loop guarantees that if the interrupt ag is set on the current thread, an exception will
be thrown, interrupting the execution of the thread.
@ThreadInterrupt supports multiple options that will let you further customize the behavior of the transformation:
http://docs.groovy-lang.org/latest/html/documentation/ 286/502
1/6/2019 Groovy Language Documentation
Attribute Default value Description Example
config =
config.addCompilationCusto
(
)
)
binding = (i
shell =
( . .class
userCode = """
try {
while (true) {
i++
}
} catch (BadException e) {
i = -1
}
"""
t = .start {
shell.evaluate(userCod
}
t.join(1000) // give at mo
to complete
binding.i > 0
(t.alive) {
t.interrupt()
}
.sleep(500)
binding.i == -1'''
http://docs.groovy-lang.org/latest/html/documentation/ 287/502
1/6/2019 Groovy Language Documentation
Attribute Default value Description Example
@groovy.transform.TimedInterrupt
The @TimedInterrupt AST transformation tries to solve a slightly di erent problem from
@groovy.transform.ThreadInterrupt : instead of checking the interrupt ag of the thread, it will automatically throw an
exception if the thread has been running for too long.
This annotation does not spawn a monitoring thread. Instead, it works in a similar manner as @ThreadInterrupt
by placing checks at appropriate places in the code. This means that if you have a thread blocked by I/O, it will not
be interrupted.
fib( n) { n<2?n:fib(n-1)+fib(n-2) }
result = fib(600)
The implementation of the famous Fibonacci number computation here is far from optimized. If it is called with a high n value, it
can take minutes to answer. With @TimedInterrupt , you can choose how long a script is allowed to run. The following setup
code will allow the user script to run for 1 second at max:
config = ()
config.addCompilationCustomizers(
(value:1, )
)
binding = (result:0)
shell = ( . .classLoader, binding,config)
@TimedInterrupt supports multiple options that will let you further customize the behavior of the transformation:
http://docs.groovy-lang.org/latest/html/documentation/ 288/502
1/6/2019 Groovy Language Documentation
Attribute Default value Description Example
http://docs.groovy-lang.org/latest/html/documentation/ 289/502
1/6/2019 Groovy Language Documentation
Attribute Default value Description Example
@groovy.transform.ConditionalInterrupt
The last annotation for safer scripting is the base annotation when you want to interrupt a script using a custom strategy. In
particular, this is the annotation of choice if you want to use resource management (limit the number of calls to an API, …). In the
following example, user code is using an in nite loop, but @ConditionalInterrupt will allow us to check a quota manager and
interrupt automatically the script:
@ConditionalInterrupt({ .disallow('user')})
{
doSomething() {
i=0
( ) {
println "Consuming resources ${++i}"
}
}
}
The quota checking is very basic here, but it can be any code:
{
quotas = [:].withDefault { 10 }
disallow( userName) {
println "Checking quota for $userName"
(quotas[userName]--)<0
}
}
We can make sure @ConditionalInterrupt works properly using this test code:
.quotas['user'] == 10
t = .start {
().doSomething()
}
t.join(5000)
!t.alive
.quotas['user'] < 0
http://docs.groovy-lang.org/latest/html/documentation/ 290/502
1/6/2019 Of course, in practice, it is unlikely that @ConditionalInterrupt will be itself
Groovy Language added by hand on user code. It can be injected in a
Documentation
similar manner as the example shown in the ThreadInterrupt section, using the
org.codehaus.groovy.control.customizers.ASTTransformationCustomizer (http://docs.groovy-lang.org/2.5.5/html/gapi/index.html?
org/codehaus/groovy/control/customizers/ASTTransformationCustomizer.html) :
config = ()
checkExpression = (
.EMPTY_ARRAY,
(
( ( .make( )), 'disallow',
('user'))
)
)
config.addCompilationCustomizers(
(value: checkExpression, )
)
userCode = """
int i=0
while (true) {
println " resources \\${++i}"
}
"""
.quotas['user'] == 10
t = .start {
shell.evaluate(userCode)
}
t.join(5000)
!t.alive
.quotas['user'] < 0
@ConditionalInterrupt supports multiple options that will let you further customize the behavior of the transformation:
http://docs.groovy-lang.org/latest/html/documentation/ 291/502
1/6/2019 Groovy Language Documentation
Attribute Default value Description Example
Compiler directives
This category of AST transformations groups annotations which have a direct impact on the semantics of the code, rather than
focusing on code generation. With that regards, they can be seen as compiler directives that either change the behavior of a
program at compile time or runtime.
@groovy.transform.Field
The @Field annotation only makes sense in the context of a script and aims at solving a common scoping error with scripts. The
following example will for example fail at runtime:
line() {
"="*x
}
x=3
"===" == line()
x=5
"=====" == line()
The error that is thrown may be di cult to interpret: groovy.lang.MissingPropertyException: No such property: x. The reason is
that scripts are compiled to classes and the script body is itself compiled as a single run() method. Methods which are de ned in
the scripts are independent, so the code above is equivalent to this:
http://docs.groovy-lang.org/latest/html/documentation/ 292/502
1/6/2019 Groovy Language Documentation
{
line() {
"="*x
}
run() {
x
x=3
"===" == line()
x=5
"=====" == line()
}
}
So def x is e ectively interpreted as a local variable, outside of the scope of the line method. The @Field AST transformation
aims at xing this by changing the scope of the variable to a eld of the enclosing script:
@Field x
line() {
"="*x
}
x=3
"===" == line()
x=5
"=====" == line()
line() {
"="*x
}
run() {
x=3
"===" == line()
x=5
"=====" == line()
}
}
@groovy.transform.PackageScope
By default, Groovy visibility rules imply that if you create a eld without specifying a modi er, then the eld is interpreted as a
property:
{
name // this is a property
}
Should you want to create a package private eld instead of a property (private eld+getter/setter), then annotate your eld with
@PackageScope :
{
@PackageScope name // not a property anymore
}
http://docs.groovy-lang.org/latest/html/documentation/ 293/502
1/6/2019 The @PackageScope annotation can also be used for classes, methods
Groovy andDocumentation
Language constructors. In addition, by specifying a list of
PackageScopeTarget values as the annotation attribute at the class level, all members within that class that don’t have an
explicit modi er and match the provided PackageScopeTarget will remain package protected. For example to apply to elds
within a class use the following annotation:
groovy.transform. .FIELDS
@PackageScope(FIELDS)
{
name // not a property, package protected
dob // not a property, package protected
age // explicit modifier, so won't be touched
}
The @PackageScope annotation is seldom used as part of normal Groovy conventions but is sometimes useful for factory
methods that should be visible internally within a package or for methods or constructors provided for testing purposes, or when
integrating with third-party libraries which require such visibility conventions.
@groovy.transform.AutoFinal
The @AutoFinal annotation instructs the compiler to automatically insert the nal modi er in numerous places within the
annotated node. If applied on a method (or constructor), the parameters for that method (or constructor) will be marked as nal.
If applied on a class de nition, the same treatment will occur for all declared methods and constructors within that class.
It is often considered bad practice to reassign parameters of a method or constructor with its body. By adding the nal modi er to
all parameter declarations you can avoid this practice entirely. Some programmers feel that adding nal everywhere increases the
amount of boilerplate code and makes the method signatures somewhat noisy. An alternative might instead be to use a code
review process or apply a codenarc (http://codenarc.org) rule (http://codenarc.sourceforge.net/codenarc-rules-
convention.html#ParameterReassignment) to give warnings if that practice is observed but these alternatives might lead to
delayed feedback during quality checking rather than within the IDE or during compilation. The @AutoFinal annotation aims to
maximise compiler/IDE feedback while retaining succinct code with minimum boilerplate noise.
The following example illustrates applying the annotation at the class level:
groovy.transform.
@AutoFinal
{
first,
( first, ) {
.first = first
. =
}
fullName( separator) {
"$first$separator$last"
}
greeting( salutation) {
"$salutation, $first"
}
}
In this example, the two parameters for the constructor and the single parameter for both the fullname and greeting
methods will be nal. Attempts to modify those parameters within the constructor or method bodies will be agged by the
compiler.
The following example illustrates applying the annotation at the method level:
http://docs.groovy-lang.org/latest/html/documentation/ 294/502
1/6/2019 Groovy Language Documentation
{
@AutoFinal
add( a, b) { a + b }
mult( a, b) { a * b }
}
Here, the add method will have nal parameters but the mult method will remain unchanged.
@groovy.transform.AnnotationCollector
@AnnotationCollector allows the creation of meta-annotations, which are described in a dedicated section.
@groovy.transform.TypeChecked
@TypeChecked activates compile-time type checking on your Groovy code. See section on type checking for details.
@groovy.transform.CompileStatic
@CompileStatic activates static compilation on your Groovy code. See section on type checking for details.
@groovy.transform.CompileDynamic
@CompileDynamic disables static compilation on parts of your Groovy code. See section on type checking for details.
@groovy.lang.DelegatesTo
@DelegatesTo is not, technically speaking, an AST transformation. It is aimed at documenting code and helping the compiler in
case you are using type checking or static compilation. The annotation is described thoroughly in the DSL section of this guide.
@groovy.transform.SelfType
@SelfType is not an AST transformation but rather a marker interface used with traits. See the traits documentation for further
details.
Swing patterns
@groovy.beans.Bindable
@Bindable is an AST transformation that transforms a regular property into a bound property (according to the JavaBeans
speci cation (http://download.oracle.com/otndocs/jcp/7224-javabeans-1.01-fr-spec-oth-JSpec/)). The @Bindable annotation can
be placed on a property or a class. To convert all properties of a class into bound properties, on can annotate the class like in this
example:
groovy.beans.
@Bindable
{
name
age
}
http://docs.groovy-lang.org/latest/html/documentation/ 295/502
1/6/2019 Groovy Language Documentation
java.beans.
java.beans.
{
$propertyChangeSupport
name
age
addPropertyChangeListener( listener) {
$propertyChangeSupport.addPropertyChangeListener(listener)
}
removePropertyChangeListener( listener) {
$propertyChangeSupport.removePropertyChangeListener(listener)
}
[] getPropertyChangeListeners() {
$propertyChangeSupport.getPropertyChangeListeners()
}
[] getPropertyChangeListeners( name) {
$propertyChangeSupport.getPropertyChangeListeners(name)
}
}
@Bindable therefore removes a lot of boilerplate from your class, dramatically increasing readability. If the annotation is put on a
single property, only that property is bound:
groovy.beans.
{
name
@Bindable age
}
@groovy.beans.ListenerList
The @ListenerList AST transformation generates code for adding, removing and getting the list of listeners to a class, just by
annotating a collection property:
java.awt. .
groovy.beans.
{
@ListenerList
< > listeners;
}
The transform will generate the appropriate add/remove methods based on the generic type of the list. In addition, it will also
create fireXXX methods based on the public methods declared on the class:
http://docs.groovy-lang.org/latest/html/documentation/ 296/502
1/6/2019 Groovy Language Documentation
java.awt. .
java.awt. .
groovy.beans.
@ListenerList
< > listeners
addActionListener( listener) {
( listener == ) {
}
( listeners == ) {
listeners = []
}
listeners.add(listener)
}
removeActionListener( listener) {
( listener == ) {
}
( listeners == ) {
listeners = []
}
listeners.remove(listener)
}
[] getActionListeners() {
__result = []
( listeners != ) {
__result.addAll(listeners)
}
(( __result ) [])
}
fireActionPerformed( param0) {
( listeners != ) {
< > __list = < >(listeners)
( listener : __list ) {
listener.actionPerformed(param0)
}
}
}
}
@Bindable supports multiple options that will let you further customize the behavior of the transformation:
@groovy.beans.Vetoable
http://docs.groovy-lang.org/latest/html/documentation/ 297/502
1/6/2019 The @Vetoable annotation works in a similar manner to Groovy
@Bindable but generates
Language constrained property according to the
Documentation
JavaBeans speci cation, instead of bound properties. The annotation can be placed on a class, meaning that all properties will be
converted to constrained properties, or on a single property. For example, annotating this class with @Vetoable :
groovy.beans.
java.beans.
java.beans.
@Vetoable
{
name
age
}
name
age
java.beans. $vetoableChangeSupport
addVetoableChangeListener( listener) {
$vetoableChangeSupport.addVetoableChangeListener(listener)
}
removeVetoableChangeListener( listener) {
$vetoableChangeSupport.removeVetoableChangeListener(listener)
}
[] getVetoableChangeListeners() {
$vetoableChangeSupport.getVetoableChangeListeners()
}
[] getVetoableChangeListeners( name) {
$vetoableChangeSupport.getVetoableChangeListeners(name)
}
setName( value) {
.fireVetoableChange('name', name, value)
name = value
}
setAge( value) {
.fireVetoableChange('age', age, value)
age = value
}
}
If the annotation is put on a single property, only that property is made vetoable:
http://docs.groovy-lang.org/latest/html/documentation/ 298/502
1/6/2019 Groovy Language Documentation
groovy.beans.
{
name
@Vetoable age
}
Test assistance
@groovy.transform.NotYetImplemented
@NotYetImplemented is used to invert the result of a JUnit 3/4 test case. It is in particular useful if a feature is not yet
implemented but the test is. In that case, it is expected that the test fails. Marking it with @NotYetImplemented will inverse the
result of the test, like in this example:
groovy.transform.
{
fib( n) {
// todo: implement later
}
}
{
@NotYetImplemented
testFib() {
dataTable = [
1:1,
2:1,
3:2,
4:3,
5:5,
6:8,
7:13
]
dataTable.each { i, r ->
.fib(i) == r
}
}
}
Another advantage of using this technique is that you can write test cases for bugs before knowing how to x them. If some time
in the future, a modi cation in the code xes a bug by side e ect, you’ll be noti ed because a test which was expected to fail
passed.
@groovy.transform.ASTTest
@ASTTest is a special AST transformation meant to help debugging other AST transformations or the Groovy compiler itself. It will
let the developer "explore" the AST during compilation and perform assertions on the AST rather than on the result of
compilation. This means that this AST transformations gives access to the AST before the bytecode is produced. @ASTTest can be
placed on any annotable node and requires two parameters:
phase: sets at which phase at which @ASTTest will be triggered. The test code will work on the AST tree at the end of this
phase.
value: the code which will be executed once the phase is reached, on the annotated node
value is a closure expression which has access to a special variable node corresponding to the annotated node, and a helper
lookup method which will be discussed here. For example, you can annotate a class node like this:
http://docs.groovy-lang.org/latest/html/documentation/ 299/502
1/6/2019 Groovy Language Documentation
groovy.transform.
org.codehaus.groovy.ast.
org.codehaus.groovy.control. .*
@ASTTest(phase=CONVERSION, value={ 1
node 2
node.name == 'Person' 3
})
{
1 we’re checking the state of the Abstract Syntax Tree after the CONVERSION phase
2 node refers to the AST node which is annotated by @ASTTest
3 it can be used to perform assertions at compile time
One interesting feature of @ASTTest is that if an assertion fails, then compilation will fail. Now imagine that we want to check the
behavior of an AST transformation at compile time. We will take @PackageScope here, and we will want to verify that a property
annotated with @PackageScope becomes a package private eld. For this, we have to know at which phase the transform runs,
which can be found in org.codehaus.groovy.transform.PackageScopeASTTransformation (http://docs.groovy-
lang.org/2.5.5/html/gapi/index.html?org/codehaus/groovy/transform/PackageScopeASTTransformation.html) : semantic analysis.
Then a test can be written like this:
groovy.transform.
groovy.transform.
org.codehaus.groovy.control. .*
@ASTTest(phase=SEMANTIC_ANALYSIS, value= {
nameNode = node.properties.find { it.name == 'name' }
ageNode = node.properties.find { it.name == 'age' }
nameNode
ageNode == // shouldn't be a property anymore
ageField = node.getDeclaredField 'age'
ageField.modifiers == 0
})
{
name
@PackageScope age
}
The @ASTTest annotation can only be placed wherever the grammar allows it. Sometimes, you would like to test the contents of
an AST node which is not annotable. In this case, @ASTTest provides a convenient lookup method which will search the AST for
nodes which are labelled with a special token:
list = lookup('anchor') 1
stmt = list[0] 2
Imagine, for example, that you want to test the declared type of a for loop variable. Then you can do it like this:
http://docs.groovy-lang.org/latest/html/documentation/ 300/502
1/6/2019 Groovy Language Documentation
groovy.transform.
groovy.transform.
org.codehaus.groovy.ast.
org.codehaus.groovy.ast.expr.
org.codehaus.groovy.ast.stmt.
org.codehaus.groovy.control. .*
{
@ASTTest(phase=SEMANTIC_ANALYSIS, value= {
forLoop = lookup('anchor')[0]
forLoop
decl = forLoop.collectionExpression.expressions[0]
decl
decl.variableExpression.name == 'i'
decl.variableExpression.originType == .int_TYPE
})
someMethod() {
x = 1;
y = 10;
anchor: ( i=0; i<x+y; i++) {
println "$i"
}
}
}
The latter is interesting if you don’t specify the phase attribute. In that case, the closure will be executed after each compile phase
after (and including) SEMANTIC_ANALYSIS . The context of the transformation is kept after each phase, giving you a chance to
check what changed between two phases.
As an example, here is how you could dump the list of AST transformations registered on a class node:
groovy.transform.
groovy.transform.
groovy.transform.
org.codehaus.groovy.ast.
org.codehaus.groovy.control.
@ASTTest(value={
.err.println "Compile phase: $compilePhase"
cn = node
.err.println "Global AST xforms:
${compilationUnit?.ASTTransformationsContext?.globalTransformNames}"
.values().each {
transforms = cn.getTransforms(it)
(transforms) {
.err.println "Ast xforms for phase $it:"
transforms.each { map ->
.err.println(map)
}
}
}
})
@CompileStatic
@Immutable
{
}
http://docs.groovy-lang.org/latest/html/documentation/ 301/502
1/6/2019 And here is how you can memorize variables for testing between two phases:
Groovy Language Documentation
groovy.transform.
groovy.transform.
org.codehaus.groovy.ast.
org.codehaus.groovy.control.
@ASTTest(value={
(compilePhase== .INSTRUCTION_SELECTION) { 1
} {
(node.getDeclaredMethods('toString') && added== ) { 3
added = compilePhase 4
}
}
})
@ToString
{
name
}
Grape handling
@groovy.lang.Grab
@groovy.lang.GrabConfig
@groovy.lang.GrabExclude
@groovy.lang.GrabResolver
@groovy.lang.Grapes
Grape is a dependency management engine embedded into Groovy, relying on several annotations which are described
thoroughly in this section of the guide.
Global transformations are applied to by the compiler on the code being compiled, wherever the transformation apply.
Compiled classes that implement global transformations are in a JAR added to the classpath of the compiler and contain
service locator le META-INF/services/org.codehaus.groovy.transform.ASTTransformation with a line with the name of
the transformation class. The transformation class must have a no-args constructor and implement the
org.codehaus.groovy.transform.ASTTransformation interface. It will be run against every source in the compilation, so
be sure to not create transformations which scan all the AST in an expansive and time-consuming manner, to keep the
compiler fast.
Local transformations are transformations applied locally by annotating code elements you want to transform. For this, we
reuse the annotation notation, and those annotations should implement
org.codehaus.groovy.transform.ASTTransformation . The compiler will discover them and apply the transformation on
these code elements.
Global transformations may be applied in any phase, but local transformations may only be applied in the semantic analysis
phase or later. Brie y, the compiler phases are:
Parsing: the grammar is used to to produce tree of tokens representing the source code
Instruction Selection: instruction set is chosen, for example Java 6 or Java 7 bytecode level
Generally speaking, there is more type information available later in the phases. If your transformation is concerned with reading
the AST, then a later phase where information is more plentiful might be a good choice. If your transformation is concerned with
writing AST, then an earlier phase where the tree is more sparse might be more convenient.
Local transformations
Local AST transformations are relative to the context they are applied to. In most cases, the context is de ned by an annotation
that will de ne the scope of the transform. For example, annotating a eld would mean that the transformation applies to the
eld, while annotating the class would mean that the transformation applies to the whole class.
As a naive and simple example, consider wanting to write a @WithLogging transformation that would add console messages at
the start and end of a method invocation. So the following "Hello World" example would actually print "Hello World" along with a
start and stop message:
@WithLogging
greet() {
println "Hello World"
}
greet()
The AST (Abstract Syntax Tree) is a tree structure consisting mostly of org.codehaus.groovy.ast.expr.Expression
(http://docs.groovy-lang.org/2.5.5/html/gapi/index.html?org/codehaus/groovy/ast/expr/Expression.html) (expressions) or
org.codehaus.groovy.ast.expr.Statement (http://docs.groovy-lang.org/2.5.5/html/gapi/index.html?
org/codehaus/groovy/ast/expr/Statement.html) (statements). An easy way to learn about the AST is to explore it in a debugger.
Once you have the AST, you can analyze it to nd out information about the code or rewrite it to add new functionality.
The local transformation annotation is the simple part. Here is the @WithLogging one:
org.codehaus.groovy.transform.
java.lang.annotation.
java.lang.annotation.
java.lang.annotation.
java.lang.annotation.
@Retention( .SOURCE)
@Target([ .METHOD])
@GroovyASTTransformationClass(["gep.WithLoggingASTTransformation"])
@interface {
}
http://docs.groovy-lang.org/latest/html/documentation/ 303/502
1/6/2019 The annotation retention can be SOURCE because you won’t needLanguage
Groovy the annotation past that. The element type here is METHOD , the
Documentation
@WithLogging because the annotation applies to methods.
But the most important part is the @GroovyASTTransformationClass annotation. This links the @WithLogging annotation to
the ASTTransformation class you will write. gep.WithLoggingASTTransformation is the fully quali ed class name of the
ASTTransformation we are going to write. This line wires the annotation to the transformation.
With this in place, the Groovy compiler is going to invoke gep.WithLoggingASTTransformation every time an @WithLogging is
found in a source unit. Any breakpoint set within LoggingASTTransformation will now be hit within the IDE when running the
sample script.
The ASTTransformation class is a little more complex. Here is the very simple, and very naive, transformation to add a method
start and stop message for @WithLogging :
@CompileStatic 1
@GroovyASTTransformation(phase= .SEMANTIC_ANALYSIS) 2
{ 3
@Override
visit( [] nodes, sourceUnit) { 4
method = ( ) nodes[1] 5
existingStatements = (( )method.code).statements 8
existingStatements.add(0, startMessage) 9
existingStatements.add(endMessage) 10
createPrintlnAst( message) { 11
(
(
("this"),
("println"),
(
(message)
)
)
)
}
}
even if not mandatory, if you write an AST transformation in Groovy, it is highly recommended to use CompileStatic
1
because it will improve performance of the compiler.
the nodes parameter is a 2 AST node array, for which the rst one is the annotation node ( @WithLogging ) and the second
5
one is the annotated node (the method node)
6 create a statement that will print a message when we enter the method
7 create a statement that will print a message when we exit the method
8 get the method body, which in this case is a BlockStatement
9 add the enter method message before the rst statement of existing code
10 append the exit method message after the last statement of existing code
11 creates an ExpressionStatement wrapping a MethodCallExpression corresponding to this.println("message")
http://docs.groovy-lang.org/latest/html/documentation/ 304/502
1/6/2019 It is important to notice that for the brevity of this example, we didn’t
Groovy make Documentation
Language the necessary checks, such as checking that the
annotated node is really a MethodNode , or that the method body is an instance of BlockStatement . This exercise is left to the
reader.
Note the creation of the new println statements in the createPrintlnAst(String) method. Creating AST for code is not always
simple. In this case we need to construct a new method call, passing in the receiver/variable, the name of the method, and an
argument list. When creating AST, it might be helpful to write the code you’re trying to create in a Groovy le and then inspect the
AST of that code in the debugger to learn what to create. Then write a function like createPrintlnAst using what you learned
through the debugger.
In the end:
@WithLogging
greet() {
println "Hello World"
}
greet()
Produces:
Starting greet
Hello World
Ending greet
It is important to note that an AST transformation participates directly in the compilation process. A common
error by beginners is to have the AST transformation code in the same source tree as a class that uses the
transformation. Being in the same source tree in general means that they are compiled at the same time. Since
the transformation itself is going to be compiled in phases and that each compile phase processes all les of the
same source unit before going to the next one, there’s a direct consequence: the transformation will not be
compiled before the class that uses it! In conclusion, AST transformations need to be precompiled before you can
use them. In general, it is as easy as having them in a separate source tree.
Global transformations
Global AST transformation are similar to local one with a major di erence: they do not need an annotation, meaning that they are
applied globally, that is to say on each class being compiled. It is therefore very important to limit their use to last resort, because
it can have a signi cant impact on the compiler performance.
Following the example of the local AST transformation, imagine that we would like to trace all methods, and not only those which
are annotated with @WithLogging . Basically, we need this code to behave the same as the one annotated with @WithLogging
before:
greet() {
println "Hello World"
}
greet()
The descriptor le is required and must be found on classpath. It will contain a single line:
META-INF/services/org.codehaus.groovy.transform.ASTTransformation
gep.
The code for the transformation looks similar to the local case, but instead of using the ASTNode[] parameter, we need to use
the SourceUnit instead:
http://docs.groovy-lang.org/latest/html/documentation/ 305/502
1/6/2019 gep/WithLoggingASTTransformation.groovy Groovy Language Documentation
@CompileStatic 1
@GroovyASTTransformation(phase= .SEMANTIC_ANALYSIS) 2
{ 3
@Override
visit( [] nodes, sourceUnit) { 4
methods = sourceUnit.AST.methods 5
existingStatements = (( )method.code).statements 9
existingStatements.add(0, startMessage) 10
existingStatements.add(endMessage) 11
}
}
createPrintlnAst( message) { 12
(
(
("this"),
("println"),
(
(message)
)
)
)
}
}
even if not mandatory, if you write an AST transformation in Groovy, it is highly recommended to use CompileStatic
1
because it will improve performance of the compiler.
the sourceUnit parameter gives access to the source being compiled, so we get the AST of the current source and retrieve
5
the list of methods from this le
6 we iterate on each method from the source le
7 create a statement that will print a message when we enter the method
8 create a statement that will print a message when we exit the method
9 get the method body, which in this case is a BlockStatement
10 add the enter method message before the rst statement of existing code
11 append the exit method message after the last statement of existing code
12 creates an ExpressionStatement wrapping a MethodCallExpression corresponding to this.println("message")
ClassCodeExpressionTransformer
It is a common use case to be able to transform an expression into another. Groovy provides a class which makes it very easy to
do this: org.codehaus.groovy.ast.ClassCodeExpressionTransformer (http://docs.groovy-lang.org/2.5.5/html/gapi/index.html?
org/codehaus/groovy/ast/ClassCodeExpressionTransformer.html)
http://docs.groovy-lang.org/latest/html/documentation/ 306/502
1/6/2019 To illustrate this, let’s create a @Shout transformation that will transform
Groovy Languageall String constants in method call arguments into
Documentation
their uppercase version. For example:
@Shout
greet() {
println "Hello World"
}
greet()
should print:
HELLO WORLD
Then the code for the transformation can use the ClassCodeExpressionTransformer to make this easier:
@CompileStatic
@GroovyASTTransformation(phase= .SEMANTIC_ANALYSIS)
{
@Override
visit( [] nodes, sourceUnit) {
trn = () { 1
inArgList =
@Override
getSourceUnit() {
sourceUnit 2
@Override
transform( exp) {
(exp ) {
inArgList =
} (inArgList &&
exp && exp.value ) {
(exp.value.toUpperCase()) 3
}
trn = .transform(exp)
inArgList =
trn
}
}
trn.visitMethod(( )nodes[1]) 4
}
}
AST Nodes
Writing an AST transformation requires a deep knowledge of the internal Groovy API. In particular it requires
knowledge about the AST classes. Since those classes are internal, there are chances that the API will change in
the future, meaning that your transformations could break. Despite that warning, the AST has been very stable
over time and such a thing rarely happens.
Classes of the Abstract Syntax Tree belong to the org.codehaus.groovy.ast package. It is recommended to the reader to use
the Groovy Console, in particular the AST browser tool, to gain knowledge about those classes. However, a good resource for
learning is the AST Builder (https://github.com/apache/groovy/tree/master/src/test/org/codehaus/groovy/ast/builder) test suite.
Macros
http://docs.groovy-lang.org/latest/html/documentation/ 307/502
1/6/2019 Introduction Groovy Language Documentation
Until version 2.5.0, when developing AST transformations, developers should have a deep knowledge about how the AST (Abstract
Syntax Tree) was built by the compiler in order to know how to add new expressions or statements during compile time.
Although the use of org.codehaus.groovy.ast.tool.GeneralUtils static methods could mitigate the burden of creating
expressions and statements, it’s still a low-level way of writing those AST nodes directly. We needed something to abstract us from
writing the AST directly and that’s exactly what Groovy macros were made for. They allow you to directly add code during
compilation, without having to translate the code you had in mind to the org.codehaus.groovy.ast.* node related classes.
@Retention( .SOURCE)
@Target([ .TYPE])
@GroovyASTTransformationClass(["metaprogramming.AddMethodASTTransformation"])
@interface { }
What would the AST transformation look like without the use of a macro ? Something like this:
@GroovyASTTransformation(phase = .INSTRUCTION_SELECTION)
{
@Override
visit( [] nodes, source) {
classNode = ( ) nodes[1]
code =
( 1
("42")) 2
methodNode =
(
"getMessage",
ACC_PUBLIC,
.make( ),
[] [],
[] [],
code) 3
classNode.addMethod(methodNode) 4
}
}
If you’re not used to the AST API, that de nitely doesn’t look like the code you had in mind. Now look how the previous code
simpli es with the use of macros.
http://docs.groovy-lang.org/latest/html/documentation/ 308/502
1/6/2019 Groovy Language Documentation
@GroovyASTTransformation(phase = .INSTRUCTION_SELECTION)
{
@Override
visit( [] nodes, source) {
classNode = ( ) nodes[1]
methodNode =
(
"getMessage",
ACC_PUBLIC,
.make( ),
[] [],
[] [],
simplestCode) 2
classNode.addMethod(methodNode) 3
}
}
Much simpler. You wanted to add a return statement that returned "42" and that’s exactly what you can read inside the
1
macro utility method. Your plain code will be translated for you to a org.codehaus.groovy.ast.stmt.ReturnStatement
2 Adding the return statement to the new method
3 Adding the new code to the annotated class
Although the macro method is used in this example to create a statement the macro method could also be used to create
expressions as well, it depends on which macro signature you use:
macro(Closure) : Create a given statement with the code inside the closure.
macro(Boolean,Closure) : if true wrap expressions inside the closure inside an statement, if false then return an expression
macro(CompilePhase, Closure) : Create a given statement with the code inside the closure in a speci c compile phase
macro(CompilePhase, Boolean, Closure) : Create an statement or an expression (true == statement, false == expression)
in a speci c compilation phase.
Sometimes we could be only interested in creating a given expression, not the whole statement, in order to do that we should use
any of the macro invocations with a boolean parameter:
http://docs.groovy-lang.org/latest/html/documentation/ 309/502
1/6/2019 Groovy Language Documentation
@GroovyASTTransformation(phase = .INSTRUCTION_SELECTION)
{
onePlusOne() {
macro( ) { 1 + 1 } 1
@Override
visit( [] nodes, source) {
classNode = nodes[1]
expression = onePlusOne() 2
returnStatement = .returnS(expression) 3
methodNode =
("getTwo",
ACC_PUBLIC,
. ,
[] [],
[] [],
returnStatement 4
classNode.addMethod(methodNode) 5
}
}
1 We’re telling macro not to wrap the expression in a statement, we’re only interested in the expression
2 Assigning the expression
3 Creating a ReturnStatement using a method from GeneralUtils and returning the expression
4 Adding the code to the new method
5 Adding the method to the class
Variable substitution
Macros are great but we can’t create anything useful or reusable if our macros couldn’t receive parameters or resolve surrounding
variables.
In the following example we’re creating an AST transformation @MD5 that when applied to a given String eld will add a method
returning the MD5 value of that eld.
@Retention( .SOURCE)
@Target([ .FIELD])
@GroovyASTTransformationClass(["metaprogramming.MD5ASTTransformation"])
@interface MD5 { }
http://docs.groovy-lang.org/latest/html/documentation/ 310/502
1/6/2019 Groovy Language Documentation
@GroovyASTTransformation(phase = .CANONICALIZATION)
MD5ASTTransformation {
@Override
visit( [] nodes, source) {
fieldNode = nodes[1]
classNode = fieldNode.declaringClass
capitalizedName = fieldNode.name.capitalize()
methodNode = (
"get${capitalizedName}MD5",
ACC_PUBLIC,
.STRING_TYPE,
[] [],
[] [],
buildMD5MethodCode(fieldNode))
classNode.addMethod(methodNode)
}
buildMD5MethodCode( fieldNode) {
fieldVar = .varX(fieldNode.name) 1
macro( .SEMANTIC_ANALYSIS, ) { 2
java.security.
.getInstance('MD5')
.digest($v { fieldVar }.getBytes()) 3
.encodeHex()
.toString()
}
}
}
If using a class outside the standard packages we should add any needed imports or use the quali ed name. When using
the quali ed named of a given static method you need to make sure it’s resolved in the proper compile phase. In this
2
particular case we’re instructing the macro to resolve it at the SEMANTIC_ANALYSIS phase, which is the rst compile phase
with type information.
In order to substitute any expression inside the macro we need to use the $v method. $v receives a closure as an
3 argument, and the closure is only allowed to substitute expressions, meaning classes inheriting
org.codehaus.groovy.ast.expr.Expression .
MacroClass
As we mentioned earlier, the macro method is only capable of producing statements and expressions . But what if we want to
produce other types of nodes, such as a method, a eld and so on?
The next example is a local transformation @Statistics . When applied to a given class, it will add two methods
getMethodCount() and getFieldCount() which return how many methods and elds within the class respectively. Here is the
marker annotation.
@Retention( .SOURCE)
@Target([ .TYPE])
@GroovyASTTransformationClass(["metaprogramming.StatisticsASTTransformation"])
@interface {}
http://docs.groovy-lang.org/latest/html/documentation/ 311/502
1/6/2019 Groovy Language Documentation
@CompileStatic
@GroovyASTTransformation(phase = .INSTRUCTION_SELECTION)
{
@Override
visit( [] nodes, source) {
classNode = ( ) nodes[1]
templateClass = buildTemplateClass(classNode) 1
classNode.addMethod(node)
}
}
@CompileDynamic
buildTemplateClass( reference) { 3
methodCount = constX(reference.methods.size()) 4
fieldCount = constX(reference.fields.size()) 5
() {
{
java.lang. getMethodCount() { 6
$v { methodCount }
}
java.lang. getFieldCount() { 7
$v { fieldCount }
}
}
}
}
}
Basically we’ve created the Statistics class as a template to avoid writing low level AST API, then we copied methods created in the
template class to their nal destination.
Types inside the MacroClass implementation should be resolved inside, that’s why we had to write
java.lang.Integer instead of simply writing Integer .
Notice that we’re using @CompileDynamic . That’s because the way we use MacroClass is like we were actually
implementing it. So if you were using @CompileStatic it will complain because an implementation of an abstract
class can’t be another di erent class.
@Macro methods
You have seen that by using macro you can save yourself a lot of work but you might wonder where that method came from. You
didn’t declare it or static import it. You can think of it as a special global method (or if you prefer, a method on every Object ). This
is much like how the println extension method is de ned. But unlike println which becomes a method selected for execution
later in the compilation process, macro expansion is done early in the compilation process. The declaration of macro as one of
the available methods for this early expansion is done by annotating a macro method de nition with the @Macro annotation and
making that method available using a similar mechanism for extension modules. Such methods are known as macro methods and
the good news is you can de ne your own.
To de ne your own macro method, create a class in a similar way to an extension module and add a method such as:
http://docs.groovy-lang.org/latest/html/documentation/ 312/502
1/6/2019 Groovy Language Documentation
{
@Macro
safe( macroContext, callExpression) {
ternaryX(
notNullX(callExpression.getObjectExpression()),
callExpression,
constX( )
);
}
...
}
Now you would register this as an extension module using a org.codehaus.groovy.runtime.ExtensionModule le within the
META-INF/groovy directory.
Now, assuming that the class and meta info le are on your classpath, you can use the macro method in the following way:
nullObject =
== safe(safe(nullObject.hashcode()).toString())
The rst tip for testing AST transformation is therefore to separate test sources from the sources of the transform. Again, this is
nothing but best practices, but you must make sure that your build too does actually compile them separately. This is the case by
default with both Apache Maven (http://maven.apache.org) and Gradle (http://gradle.org).
A very easy workaround is to use the GroovyTestCase class which provides an assertScript method. This means that instead
of writing this in a test case:
{
@MyTransformToDebug
methodToBeTested() {}
}
testMyTransform() {
c = ()
c.methodToBeTested()
}
http://docs.groovy-lang.org/latest/html/documentation/ 313/502
1/6/2019 Groovy Language Documentation
testMyTransformWithBreakpoint() {
assertScript '''
import metaprogramming.MyTransformToDebug
class Subject {
@MyTransformToDebug
void methodToBeTested() {}
}
def c = new Subject()
c.methodToBeTested()
'''
}
The di erence is that when you use assertScript , the code in the assertScript block is compiled when the unit test is
executed. That is to say that this time, the Subject class will be compiled with debugging active, and the breakpoint is going to
be hit.
ASTMatcher
Sometimes you may want to make assertions over AST nodes; perhaps to lter the nodes, or to make sure a given transformation
has built the expected AST node.
Filtering nodes
For instance if you would like to apply a given transformation only to a speci c set of AST nodes, you could use ASTMatcher to
lter these nodes. The following example shows how to transform a given expression to another. Using ASTMatcher it looks for a
speci c expression 1 + 1 and it transforms it to 3 . That’s why we called it the @Joking example.
First we create the @Joking annotation that only can be applied to methods:
@Retention( .SOURCE)
@Target([ .METHOD])
@GroovyASTTransformationClass(["metaprogramming.JokingASTTransformation"])
@interface { }
@CompileStatic
@GroovyASTTransformation(phase = .INSTRUCTION_SELECTION)
{
@Override
visit( [] nodes, source) {
methodNode = ( ) nodes[1]
methodNode
.getCode()
.visit( (source)) 1
}
}
1 Get the method’s code statement and apply the expression transformer
And this is when the ASTMatcher is used to apply the transformation only to those expressions matching the expression 1 + 1 .
http://docs.groovy-lang.org/latest/html/documentation/ 314/502
1/6/2019 Groovy Language Documentation
{
sourceUnit
( sourceUnit) {
.sourceUnit = sourceUnit
}
@Override
transform( exp) {
= macro { 1 + 1 } 1
( .matches( , exp)) { 2
macro { 3 } 3
.transform(exp)
}
}
metaprogramming
{
@Joking
getResult() {
1 + 1
}
}
().result == 3
Normally we test AST transformations just checking that the nal use of the transformation does what we expect. But it would be
great if we could have an easy way to check, for example, that the nodes the transformation adds are what we expected from the
beginning.
http://docs.groovy-lang.org/latest/html/documentation/ 315/502
1/6/2019 Groovy Language Documentation
@GroovyASTTransformation(phase = .INSTRUCTION_SELECTION)
{
VAR_X = 'x'
@Override
visit( [] nodes, source) {
classNode = ( ) nodes[1]
giveMeTwo = getTemplateClass(sumExpression)
.getDeclaredMethods('giveMeTwo')
.first()
classNode.addMethod(giveMeTwo) 1
getSumExpression() { 2
macro {
$v{ varX(VAR_X) } +
$v{ varX(VAR_X) }
}
}
getTemplateClass( expression) { 3
() {
{
java.lang. giveMeTwo(java.lang. x) {
$v { expression }
}
}
}
}
}
Building a binary expression. The binary expression uses the same variable expression in both sides of the + token (check
2
varX method at org.codehaus.groovy.ast.tool.GeneralUtils).
3 Builds a new ClassNode with a method called giveMeTwo which returns the result of an expression passed as parameter.
Now instead of creating a test executing the transformation over a given sample code. I would like to check that the construction
of the binary expression is done properly:
testTestingSumExpression() {
( ) { 1
sample = ()
referenceNode = macro {
a + a 2
}.withConstraints { 3
placeholder 'a' 4
sample
.sumExpression
.matches(referenceNode) 5
}
}
@Twice
class AAA {
ASTTest
Last but not least, testing an AST transformation is also about testing the state of the AST during compilation. Groovy provides a
tool named @ASTTest for this: it is an annotation that will let you add assertions on an abstract syntax tree. Please check the
documentation for ASTTest for more details.
External references
If you are interested in a step-by-step tutorial about writing AST transformations, you can follow this workshop
(http://melix.github.io/ast-workshop/).
Add a Dependency
Grape is a JAR dependency manager embedded into Groovy. Grape lets you quickly add maven repository dependencies to your
classpath, making scripting even easier. The simplest use is as simple as adding an annotation to your script:
@Grab('org.springframework:spring-orm:3.2.5.RELEASE')
org.springframework.jdbc.core.
Note that we are using an annotated import here, which is the recommended way. You can also search for dependencies on
mvnrepository.com (http://mvnrepository.com) and it will provide you the @Grab annotation form of the pom.xml entry.
@GrabResolver(name='restlet', root='http://maven.restlet.org/')
@Grab( ='org.restlet', ='org.restlet', version='1.1.6')
@Grab('net.sourceforge.htmlunit:htmlunit:2.8')
@GrabExclude('xml-apis:xml-apis')
JDBC Drivers
http://docs.groovy-lang.org/latest/html/documentation/ 317/502
1/6/2019 Because of the way JDBC drivers are loaded, you’ll need toGroovy
con gure Grape Documentation
Language to attach JDBC driver dependencies to the system class
loader. I.e:
@GrabConfig(systemClassLoader= )
@Grab( ='mysql', ='mysql-connector-java', version='5.1.6')
Proxy settings
If you are behind a rewall and/or need to use Groovy/Grape through a proxy server, you can specify those settings on the
command like via the http.proxyHost and http.proxyPort system properties:
Or you can make this system wide by adding these properties to your JAVA_OPTS environment variable:
Logging
If you want to see what Grape is doing set the system property groovy.grape.report.downloads to true (e.g. add
-Dgroovy.grape.report.downloads=true to invocation or JAVA_OPTS) and Grape will print the following infos to System.error:
To log with even more verbosity, increase the Ivy log level (defaults to -1 ). For example -Divy.message.logger.level=4 .
3.5.2. Detail
Grape (The Groovy Adaptable Packaging Engine or Groovy Advanced Packaging Engine) is the infrastructure enabling the grab()
calls in Groovy, a set of classes leveraging Ivy (http://ant.apache.org/ivy/) to allow for a repository driven module system for
Groovy. This allows a developer to write a script with an essentially arbitrary library requirement, and ship just the script. Grape
will, at runtime, download as needed and link the named libraries and all dependencies forming a transitive closure when the
script is run from existing repositories such as JCenter, Ibiblio and java.net.
Grape follows the Ivy conventions for module version identi cation, with naming change.
group - Which module group the module comes from. Translates directly to a Maven groupId or an Ivy Organization. Any
group matching /groovy[x][\..*]^/ is reserved and may have special meaning to the groovy endorsed modules.
module - The name of the module to load. Translated directly to a Maven artifactId or an Ivy artifact.
version - The version of the module to use. Either a literal version `1.1-RC3' or an Ivy Range `[2.2.1,)' meaning 2.2.1 or any
greater version).
The downloaded modules will be stored according to Ivy’s standard mechanism with a cache root of ~/.groovy/grapes
3.5.3. Usage
Annotation
One or more groovy.lang.Grab annotations can be added at any place that annotations are accepted to tell the compiler that
this code relies on the speci c library. This will have the e ect of adding the library to the classloader of the groovy compiler. This
annotation is detected and evaluated before any other resolution of classes in the script, so imported classes can be properly
resolved by a @Grab annotation.
http://docs.groovy-lang.org/latest/html/documentation/ 318/502
1/6/2019 Groovy Language Documentation
com.jidesoft.swing.
@Grab( ='com.jidesoft', ='jide-oss', version='[2.2.1,2.3.0)')
{
testMethod () {
. .name
}
}
An appropriate grab(…) call will be added to the static initializer of the class of the containing class (or script class in the case of
an annotated script element).
@Grapes([
@Grab( ='commons-primitives', ='commons-primitives', version='1.0'),
@Grab( ='org.ccil.cowan.tagsoup', ='tagsoup', version='0.9.7')])
{
// ...
}
Technical notes:
Originally, Groovy stored the Grab annotations for access at runtime and duplicates aren’t allowed in the bytecode. In current
versions, @Grab has only SOURCE retention, so the multiple occurrences aren’t an issue.
Future versions of Grape may support using the Grapes annotation to provide a level of structuring, e.g. allowing a
GrabExclude or GrabResolver annotation to apply to only a subset of the Grab annotations.
Method call
Typically a call to grab will occur early in the script or in class initialization. This is to insure that the libraries are made available to
the ClassLoader before the groovy code relies on the code. A couple of typical calls may appear as follows:
groovy.grape.
// random maven library
.grab( :'com.jidesoft', :'jide-oss', version:'[2.2.0,)')
.grab([ :'org.apache.ivy', :'ivy', version:'2.0.0-beta1', conf:['default',
'optional']],
[ :'org.apache.ant', :'ant', version:'1.7.0'])
Multiple calls to grab in the same context with the same parameters should be idempotent. However, if the same code is called
with a di erent ClassLoader context then resolution may be re-run.
If the args map passed into the grab call has an attribute noExceptions that evaluates true no exceptions will be thrown.
grab requires that a RootLoader or GroovyClassLoader be speci ed or be in the ClassLoader chain of the calling class.
By default failure to have such a ClassLoader available will result in module resolution and an exception being thrown
The ClassLoader passed in via the classLoader: argument and it’s parent classloaders.
The ClassLoader of the object passed in as the referenceObject: argument, and it’s parent classloaders.
grab(HashMap) Parameters
group: - <String> - Which module group the module comes from. Translates directly to a Maven groupId. Any group matching
/groovy(|\..|x|x\..)/ is reserved and may have special meaning to the groovy endorsed modules.
http://docs.groovy-lang.org/latest/html/documentation/ 319/502
1/6/2019 module: - <String> - The name of the module to load.Groovy
Translated directly
Language to a Maven artifactId.
Documentation
version: - <String> and possibly <Range> - The version of the module to use. Either a literal version `1.1-RC3' or an Ivy Range
`[2.2.1,)' meaning 2.2.1 or any greater version).
force: - <boolean>, defaults true - Used to indicate that this revision must be used in case of con icts, independently of
changing: - <boolean>, default false - Whether the artifact can change without it’s version designation changing.
transitive: - <boolean>, default true - Whether to resolve other dependencies this module has or not.
There are two principal variants of grab , one with a single Map and one with an arguments Map and multiple dependencies map.
A call to the single map grab is the same as calling grab with the same map passed in twice, so grab arguments and dependencies
can be mixed in the same map, and grab can be called as a single method with named parameters.
There are synonyms for these parameters. Submitting more than one is a runtime exception.
refObject: - <Object> - The closest parent ClassLoader for the object’s class will be treated as though it were passed in as
classLoader:
validate: - <boolean>, default false - Should poms or ivy les be validated (true), or should we trust the cache (false).
noExceptions: - <boolean>, default false - If ClassLoader resolution or repository querying fails, should we throw an
exception (false) or fail silently (true).
This installs the speci ed groovy module or maven artifact. If a version is speci ed that speci c version will be installed, otherwise
the most recent version will be used (as if `*' we passed in).
grape list
Lists locally installed modules (with their full maven name in the case of groovy modules) and versions.
This returns the le locations of the jars representing the artifacts for the speci ed module(s) and the respective transitive
dependencies. You may optionally pass in -ant, -dos, or -shell to get the dependencies expressed in a format applicable for an ant
script, windows batch le, or unix shell script respectively. -ivy may be passed to see the dependencies expressed in an ivy like
format.
This uninstalls a particular grape: it non-transitively removes the respective jar le from the grape cache.
For more information on how to customize these settings, please refer to the Ivy documentation
(https://ant.apache.org/ivy/history/latest-milestone/index.html).
More Examples
Using Apache Commons Collections:
createEmptyInts() { () }
ints = createEmptyInts()
ints.add(0, 42)
ints.size() == 1
ints. (0) == 42
Using TagSoup:
com.google.common.collect.
@Grab( ='com.google.code.google-collections', ='google-collect', version='snapshot-
20080530')
getFruit() { [grape:'purple', lemon:'yellow', orange:'orange'] }
fruit.lemon == 'yellow'
fruit.inverse().yellow == 'lemon'
http://docs.groovy-lang.org/latest/html/documentation/ 321/502
1/6/2019 Groovy Language Documentation
@Grab('org.eclipse.jetty.aggregate:jetty-server:8.1.19.v20160209')
@Grab('org.eclipse.jetty.aggregate:jetty-servlet:8.1.19.v20160209')
@Grab('javax.servlet:javax.servlet-api:3.0.1')
org.eclipse.jetty.server.
org.eclipse.jetty.servlet.
groovy.servlet.
runServer(duration) {
server = (8080)
context = (server, "/", .SESSIONS)
context.resourceBase = "."
context.addServlet( , "*.gsp")
server.start()
sleep duration
server.stop()
}
runServer(10000)
Grape will download Jetty and its dependencies on rst launch of this script, and cache them. We create a new Jetty Server on port
8080, then expose Groovy’s TemplateServlet at the root of the context — Groovy comes with its own powerful template engine
mechanism. We start the server and let it run for a certain duration. Each time someone will hit
http://localhost:8080/somepage.gsp, it will display the somepage.gsp template to the user — those template pages should be
situated in the same directory as this server script.
This chapter will start with language speci c testing features and continue with a closer look at JUnit integration, Spock for
speci cations, and Geb for functional tests. Finally, we’ll do an overview of other testing libraries known to be working with
Groovy.
Power Assertions
Writing tests means formulating assumptions by using assertions. In Java this can be done by using the assert keyword that has
been added in J2SE 1.4. In Java, assert statements can be enabled via the JVM parameters -ea (or -enableassertions ) and
-da (or -disableassertions ). Assertion statements in Java are disabled by default.
Groovy comes with a rather powerful variant of assert also known as power assertion statement. Groovy’s power assert
di ers from the Java version in its output given the boolean expression validates to false :
x = 1
x == 2
// Output: 1
//
// Assertion failed:
// assert x == 2
// | |
// 1 false
The java.lang.AssertionError that is thrown whenever the assertion can not be validated successfully, contains an extended
version of the original exception message. The power assertion output shows evaluation results from the outer to the inner
expression.
http://docs.groovy-lang.org/latest/html/documentation/ 322/502
1/6/2019 The power assertion statements true power unleashes in Groovy
complex Boolean Documentation
Language statements, or statements with collections or other
toString -enabled classes:
x = [1,2,3,4,5]
(x << 6) == [6,7,8,9,10]
// Output:
//
// Assertion failed:
// assert (x << 6) == [6,7,8,9,10]
// | | |
// | | false
// | [1, 2, 3, 4, 5, 6]
// [1, 2, 3, 4, 5, 6]
Another important di erence from Java is that in Groovy assertions are enabled by default. It has been a language design decision
to remove the possibility to deactivate assertions. Or, as Bertrand Meyer stated,
it makes no sense to take off your swim ring if you put your feet into real water .
One thing to be aware of are methods with side-e ects inside Boolean expressions in power assertion statements. As the internal
error message construction mechanism does only store references to instances under target, it happens that the error message
text is invalid at rendering time in case of side-e ecting methods involved:
[[1,2,3,3,3,3,4]].first().unique() == [1,2,3]
// Output:
//
// Assertion failed:
// assert [[1,2,3,3,3,3,4]].first().unique() == [1,2,3]
// | | |
// | | false
// | [1, 2, 3, 4]
// [1, 2, 3, 4] 1
1 The error message shows the actual state of the collection, not the state before the unique method was applied
If you choose to provide a custom assertion error message this can be done by using the Java syntax
assert expression1 : expression2 where expression1 is the Boolean expression and expression2 is the
custom error message. Be aware though that this will disable the power assert and will fully fallback to custom
error messages on assertion errors.
The following sections show ways to create mocks and stubs with Groovy language features only.
Map Coercion
By using maps or expandos, we can incorporate desired behaviour of a collaborator very easily as shown here:
{
convert( key) {
"test"
}
}
http://docs.groovy-lang.org/latest/html/documentation/ 323/502
1/6/2019 The as operator can be used to coerce a map to a particular class.
Groovy The given
Language map keys are interpreted as method names and the
Documentation
values, being groovy.lang.Closure blocks, are interpreted as method code blocks.
Be aware that map coercion can get into the way if you deal with custom java.util.Map descendant classes in
combination with the as operator. The map coercion mechanism is targeted directly at certain collection classes,
it doesn’t take custom classes into account.
Closure Coercion
The 'as' operator can be used with closures in a neat way which is great for developer testing in simple scenarios. We haven’t
found this technique to be so powerful that we want to do away with dynamic mocking, but it can be very useful in simple cases
none-the-less.
Classes or interfaces holding a single method, including SAM (single abstract method) classes, can be used to coerce a closure
block to be an object of the given type. Be aware that for doing this, Groovy internally create a proxy object descending for the
given class. So the object will not be a direct instance of the given class. This important if, for example, the generated proxy
object’s meta-class is altered afterwards.
Groovy supports a feature called implicit SAM coercion. This means that the as operator is not necessary in situations where the
runtime can infer the target SAM type. This type of coercion might be useful in tests to mock entire SAM classes:
{
doSomething()
}
The MockFor class supports (typically unit) testing of classes in isolation by allowing a strictly ordered expectation of the behavior
of collaborators to be de ned. A typical test scenario involves a class under test and one or more collaborators. In such a scenario
it is often desirable to just test the business logic of the class under test. One strategy for doing that is to replace the collaborator
instances with simpli ed mock objects to help isolate out the logic in the test target. MockFor allows such mocks to be created
using meta-programming. The desired behavior of collaborators is de ned as a behavior speci cation. The behavior is enforced
and checked automatically.
{
first,
}
{
father, mother
nameOfMother() { "$mother.first $mother.last" }
}
With MockFor , a mock expectation is always sequence dependent and its use automatically ends with a call to verify :
http://docs.groovy-lang.org/latest/html/documentation/ 324/502
1/6/2019 Groovy Language Documentation
mock = ( ) 1
mock.demand.getFirst{ 'dummy' }
mock.demand.getLast{ 'name' }
mock. { 2
The StubFor class supports (typically unit) testing of classes in isolation by allowing a loosely-ordered expectation of the behavior
of collaborators to be de ned. A typical test scenario involves a class under test and one or more collaborators. In such a scenario
it is often desirable to just test the business logic of the CUT. One strategy for doing that is to replace the collaborator instances
with simpli ed stub objects to help isolate out the logic in the target class. StubFor allows such stubs to be created using meta-
programming. The desired behavior of collaborators is de ned as a behavior speci cation.
In contrast to MockFor the stub expectation checked with verify is sequence independent and its use is optional:
stub = ( ) 1
stub.demand. { 2
getLast{ 'name' }
getFirst{ 'dummy' }
}
stub. { 3
MockFor and StubFor can not be used to test statically compiled classes e.g for Java classes or Groovy classes that make use of
@CompileStatic . To stub and/or mock these classes you can use Spock or one of the Java mocking libraries.
Every java.lang.Class is supplied with a special metaClass property that will give a reference to an ExpandoMetaClass
instance. The expando meta-class is not restricted to custom classes, it can be used for JDK classes like for example
java.lang.String as well:
http://docs.groovy-lang.org/latest/html/documentation/ 325/502
1/6/2019 Groovy Language Documentation
.metaClass.swapCase = {->
sb = ()
.each {
sb << ( .isUpperCase(it ) ? .toLowerCase(it ) :
.toUpperCase(it ))
}
sb.toString()
}
s = "heLLo, worLD!"
s.swapCase() == 'HEllO, WORld!'
The ExpandoMetaClass is a rather good candidate for mocking functionality as it allows for more advanced stu like mocking
static methods
{
title
}
b = .create("The Stand")
b.title == 'The Stand'
or even constructors
b = ("The Stand")
b.title == 'The Stand'
Mocking constructors might seem like a hack that’s better not even to be considered but even there might be valid
use cases. An example can be found in Grails where domain class constructors are added at run-time with the
help of ExpandoMetaClass . This lets the domain object register itself in the Spring application context and allows
for injection of services or other beans controlled by the dependency-injection container.
If you want to change the metaClass property on a per test method level you need to remove the changes that were done to the
meta-class, otherwise those changes would be persistent across test method calls. Changes are removed by replacing the meta-
class in the GroovyMetaClassRegistry :
.metaClassRegistry.setMetaClass(java.lang. , )
Another alternative is to register a MetaClassRegistryChangeEventListener , track the changed classes and remove the
changes in the cleanup method of your chosen testing runtime. A good example can be found in the Grails web development
framework (https://github.com/grails/grails-core/blob/master/grails-
bootstrap/src/main/groovy/grails/build/support/MetaClassRegistryCleaner.java).
Besides using the ExpandoMetaClass on a class-level, there is also support for using the meta-class on a per-object level:
In this case the meta-class change is related to the instance only. Depending on the test scenario this might be a better t than the
global meta-class change.
GDK Methods
The following section gives a brief overview on GDK methods that can be leveraged in test case scenarios, for example for test
data generation.
http://docs.groovy-lang.org/latest/html/documentation/ 326/502
1/6/2019 Iterable#combinations Groovy Language Documentation
The combinations method that is added on java.lang.Iterable compliant classes can be used to get a list of combinations
from a list containing two or more sub-lists:
testCombinations() {
combinations = [[2, 3],[4, 5, 6]].combinations()
combinations == [[2, 4], [3, 4], [2, 5], [3, 5], [2, 6], [3, 6]]
}
The method could be used in test case scenarios to generate all possible argument combinations for a speci c method call.
Iterable#eachCombination
The eachCombination method that is added on java.lang.Iterable can be used to apply a function (or in this case a
groovy.lang.Closure ) to each if the combinations that has been built by the combinations method:
eachCombination is a GDK method that is added to all classes conforming to the java.lang.Iterable interface. It applies a
function on each combination of the input lists:
testEachCombination() {
[[2, 3],[4, 5, 6]].eachCombination { println it[0] + it[1] }
}
The method could be used in the testing context to call methods with each of the generated combinations.
Tool Support
Various frameworks and build tools come with Cobertura integration. For Grails, there is the code coverage plugin
(http://grails.org/plugin/code-coverage) based on Cobertura, for Gradle there is the gradle-cobertura plugin
(https://github.com/eriwen/gradle-cobertura-plugin), to name only two of them.
The following code listing shows an example on how to enable Cobertura test coverage reports in a Gradle build script from a
Groovy project:
http://docs.groovy-lang.org/latest/html/documentation/ 327/502
1/6/2019 Groovy Language Documentation
pluginVersion = '<plugin version>'
groovyVersion = '<groovy version>'
junitVersion = '<junit version>'
buildscript {
repositories {
mavenCentral()
}
dependencies {
classpath 'com.eriwen:gradle-cobertura-plugin:${pluginVersion}'
}
}
repositories {
mavenCentral()
}
dependencies {
compile "org.codehaus.groovy:groovy-all:${groovyVersion}"
testCompile "junit:junit:${junitVersion}"
}
cobertura {
format = 'html'
includes = ['**/*.java', '**/*.groovy']
excludes = ['com/thirdparty/**/*.*']
}
Several output formats can be chosen for Cobertura coverage reports and test code coverage reports can be added to continuous
integration build tasks.
You use the same overall practices as you would when testing with Java but you can adopt much of Groovy’s concise syntax in
your tests making them succinct. You can even use the capabilities for writing testing domain speci c languages (DSLs) if you
feel so inclined.
There are numerous helper classes that simplify many testing activities. The details di er in some cases depending on the
version of JUnit you are using. We’ll cover those details shortly.
Groovy deems that tests are so important you should be able to run them as easily as scripts or classes. This is why Groovy
includes an automatic test runner when using the groovy command or the GroovyConsole. This gives you some additional
options over and above running your tests
In the following sections we will have a closer look at JUnit 3, 4 and 5 Groovy integration.
JUnit 3
Maybe one of the most prominent Groovy classes supporting JUnit 3 tests is the GroovyTestCase class. Being derived from
junit.framework.TestCase it o ers a bunch of additional methods that make testing in Groovy a breeze.
Although GroovyTestCase inherits from TestCase doesn’t mean you can’t use JUnit 4 features in your project.
In fact, the most recent Groovy versions come with a bundled JUnit 4 and that comes with a backwards compatible
TestCase implementation. There have been some discussion on the Groovy mailing-list on whether to use
GroovyTestCase or JUnit 4 with the result that it is mostly a matter of taste, but with GroovyTestCase you get a
bunch of methods for free that make certain types of tests easier to write.
In this section, we will have a look at some of the methods provided by GroovyTestCase . A full list of these can be found in the
JavaDoc documentation for groovy.util.GroovyTestCase (http://docs.groovy-lang.org/2.5.5/html/gapi/index.html?
groovy/util/GroovyTestCase.html) , don’t forget it is inherited from junit.framework.TestCase which inherits all the assert*
http://docs.groovy-lang.org/latest/html/documentation/ 328/502
1/6/2019 methods. Groovy Language Documentation
Assertion Methods
GroovyTestCase is inherited from junit.framework.TestCase therefore it inherits a large number of assertion methods being
available to be called in every test method:
testAssertions() {
assertTrue(1 == 1)
assertEquals("test", "test")
x = "42"
assertNotNull "x must not be null", x
assertNull
assertSame x, x
}
As can be seen above, in contrast to Java it is possible to leave out the parenthesis in most situations which leads to even more
readability of JUnit assertion method call expressions.
An interesting assertion method that is added by GroovyTestCase is assertScript . It ensures that the given Groovy code
string succeeds without any exception:
testScriptAssertions() {
assertScript '''
def x = 1
def y = 2
assert x + y == 3
'''
}
shouldFail Methods
shouldFail can be used to check whether the given code block fails or not. In case it fails, the assertion does hold, otherwise the
assertion fails:
testInvalidIndexAccess1() {
numbers = [1,2,3,4]
shouldFail {
numbers. (4)
}
}
The example above uses the basic shouldFail method interface that takes a groovy.lang.Closure as a single argument. The
Closure instance holds the code that is supposed to be breaking during run-time.
If we wanted to assert shouldFail on a speci c java.lang.Exception type we could have done so by using the shouldFail
implementation that takes the Exception class as rst argument and the Closure as second argument:
testInvalidIndexAccess2() {
numbers = [1,2,3,4]
shouldFail , {
numbers. (4)
}
}
If anything other than IndexOutOfBoundsException (or a descendant class of it) is thrown, the test case will fail.
http://docs.groovy-lang.org/latest/html/documentation/ 329/502
1/6/2019 A pretty nice feature of shouldFail hasn’t been visible so far: it Language
Groovy returns the exception message. This is really useful if you want to
Documentation
assert on the exception error message:
testInvalidIndexAccess3() {
numbers = [1,2,3,4]
msg = shouldFail , {
numbers. (4)
}
msg.contains('Index: 4, Size: 4') ||
msg.contains('Index 4 out-of-bounds for length 4') ||
msg.contains('Index 4 out of bounds for length 4')
}
notYetImplemented Method
The notYetImplemented method has been greatly in uenced by HtmlUnit. It allows to write a test method but mark it as not yet
implemented. As long as the test method fails and is marked with notYetImplemented the test goes green:
testNotYetImplemented1() {
(notYetImplemented()) 1
1 == 2 2
1 a call to notYetImplemented is necessary for GroovyTestCase to get the current method stack.
2 as long as the test evaluates to false the test execution will be successful.
An alternative to the notYetImplemented method is the @NotYetImplemented annotation. It allows for annotating a method as
not yet implemented, with the exact same behavior as GroovyTestCase#notYetImplemented but without the need for the
notYetImplemented method call:
@NotYetImplemented
testNotYetImplemented2() {
1 == 2
}
JUnit 4
Groovy can be used to write JUnit 4 test cases without any restrictions. The groovy.test.GroovyAssert holds various static
methods that can be used as replacement for the GroovyTestCase methods in JUnit 4 tests:
org.junit.
groovy.test. .shouldFail
@Test
indexOutOfBoundsAccess() {
numbers = [1,2,3,4]
shouldFail {
numbers. (4)
}
}
As can be seen in the example above, the static methods found in GroovyAssert are imported at the beginning of the class
de nition thus shouldFail can be used the same way it can be used in a GroovyTestCase .
http://docs.groovy-lang.org/latest/html/documentation/ 330/502
1/6/2019 Groovy Language Documentation
groovy.test.GroovyAssert descends from org.junit.Assert that means it inherits all JUnit assertion
methods. However, with the introduction of the power assertion statement, it turned out to be good practice to
rely on assertion statements instead of using the JUnit assertion methods with the improved message being the
main reason.
@Test
shouldFailReturn() {
e = shouldFail {
('foo',
('bar'))
}
e
e.message == 'foo'
e.cause.message == 'bar'
}
JUnit 5
Much of the approach and helper classes described under JUnit4 apply when using JUnit5 however JUnit5 uses some slightly
di erent class annotations when writing your tests. See the JUnit5 (http://junit.org) documentation for more details.
Create your test classes as per normal JUnit5 guidelines as shown in this example:
{
@Test
streamSum() {
.of(1, 2, 3).mapToInt{ i -> i }.sum() > 5
}
isPalindrome(s) { s == s.reverse() }
@ParameterizedTest 1
@TestFactory
dynamicTestCollection() {[
dynamicTest("Add test") { -> 1 + 1 == 2 },
dynamicTest("Multiply Test") { -> 2 * 3 == 6 }
]}
}
1 This test requires the additional org.junit.jupiter:junit-jupiter-params dependency if not already in your project.
You can run the tests in your IDE or build tool if it supports and is con gured for JUnit5. If you run the above test in the
GroovyConsole or via the groovy command, you will see a short text summary of the result of running the test:
More detailed information is available at the FINE logging level. You can con gure your logging to display such information or do
it programmatically as follows:
http://docs.groovy-lang.org/latest/html/documentation/ 331/502
1/6/2019 Groovy Language Documentation
@BeforeAll
init() {
logger = .getLogger( .name)
logger.level = .FINE
logger.addHandler( (level: .FINE))
}
Beside these awesome features Spock is a good example on how to leverage advanced Groovy programming
language features in third party libraries, for example, by using Groovy AST transformations.
This section should not serve as detailed guide on how to use Spock, it should rather give an impression what
Spock is about and how it can be leveraged for unit, integration, functional or any other type of testing.
The next section we will have an rst look at the anatomy of a Spock speci cation. It should give a pretty good feeling on what
Spock is up to.
Speci cations
Spock lets you write speci cations that describe features (properties, aspects) exhibited by a system of interest. The "system" can
be anything between a single class and an entire application, a more advanced term for it is system under speci cation. The
feature description starts from a speci c snapshot of the system and its collaborators, this snapshot is called the feature’s xture.
Spock speci cation classes are derived from spock.lang.Specification . A concrete speci cation class might consist of elds,
xture methods, features methods and helper methods.
Let’s have a look at a simple speci cation with a single feature method for an imaginary Stack class:
stack = ()
: 3
stack.push 42
: 4
stack.size() == 1
}
}
Spock feature speci cations are de ned as methods inside a spock.lang.Specification class. They describe the feature by
using a String literal instead of a method name.
A feature method holds multiple blocks, in our example we used setup , when and then . The setup block is special in that it is
optional and allows to con gure local variables visible inside the feature method. The when block de nes the stimulus and is a
companion of the then block which describes the response to the stimulus.
Note that the setup method in the StackSpec above additionally has a description String. Description Strings are optional and
can be added after block labels (like setup , when , then ).
http://docs.groovy-lang.org/latest/html/documentation/ 332/502
1/6/2019 More Spock Groovy Language Documentation
Spock provides much more features like data tables or advanced mocking capabilities. Feel free to consult the Spock GitHub page
(https://github.com/spockframework/spock) for more documentation and download information.
Geb has great features that make it a good t for a functional testing library:
support for modularization of certain web components (e.g. menu-bars, etc.) with modules
This section should not serve as detailed guide on how to use Geb, it should rather give an impression what Geb is
about and how it can be leveraged functional testing.
The next section will give an example on how Geb can be used to write a functional test for a simple web page with a single search
eld.
A Geb Script
Although Geb can be used standalone in a Groovy script, in many scenarios it’s used in combination with other testing
frameworks. Geb comes with various base classes that can be used in JUnit 3, 4, TestNG or Spock tests. The base classes are part
of additional Geb modules that need to be added as a dependency.
For example, the following @Grab dependencies have to be used to run Geb with the Selenium Firefox driver in JUnit4 tests. The
module that is needed for JUnit 3/4 support is geb-junit :
@Grapes([
@Grab("org.gebish:geb-core:0.9.2"),
@Grab("org.gebish:geb-junit:0.9.2"),
@Grab("org.seleniumhq.selenium:selenium-firefox-driver:2.26.0"),
@Grab("org.seleniumhq.selenium:selenium-support:2.26.0")
])
The central class in Geb is the geb.Browser class. As its name implies it is used to browse pages and access DOM elements:
browser.drive {
go "/login" 2
$("#username").text = 'John' 3
$("#password").text = 'Doe'
$("#loginButton").click()
1 A new Browser instance is created. In this case it uses the Selenium FirefoxDriver and sets the baseUrl .
2 go is used to navigate to an URL or relative URI
3 $ together with CSS selectors is used to access the username and password DOM elds.
The Browser class comes with a drive method that delegates all method/property calls to the current browser instance. The
Browser con guration must not be done inline, it can also be externalized in a GebConfig.groovy con guration le for
example. In practice, the usage of the Browser class is mostly hidden by Geb test base classes. They delegate all missing
properties and method calls to the current browser instance that exists in the background:
http://docs.groovy-lang.org/latest/html/documentation/ 333/502
1/6/2019 Groovy Language Documentation
geb.junit4. {
@Test
executeSeach() {
go 'http://somehost/mayapp/search' 1
$('#searchButton').click() 3
}
}
The example above shows a simple Geb web test with the JUnit 4 base class geb.junit4.GebTest . Note that in this case the
Browser con guration is externalized. GebTest delegates methods like go and $ to the underlying browser instance.
More Geb
In the previous section we only scratched the surface of the available Geb features. More information on Geb can be found at the
project homepage (http://gebish.org).
3.7.1. JsonSlurper
JsonSlurper is a class that parses JSON text or reader content into Groovy data structures (objects) such as maps, lists and
primitive types like Integer , Double , Boolean and String .
The class comes with a bunch of overloaded parse methods plus some special methods such as parseText , parseFile and
others. For the next example we will use the parseText method. It parses a JSON String and recursively converts it to a list or
map of objects. The other parse* methods are similar in that they return a JSON String but for di erent parameter types.
jsonSlurper = ()
= jsonSlurper.parseText('{ "name": "John Doe" } /* some comment */')
Notice the result is a plain map and can be handled like a normal Groovy object instance. JsonSlurper parses the given JSON as
de ned by the ECMA-404 JSON Interchange Standard (http://www.ecma-international.org/publications/ les/ECMA-ST/ECMA-
404.pdf) plus support for JavaScript comments and dates.
In addition to maps JsonSlurper supports JSON arrays which are converted to lists.
jsonSlurper = ()
= jsonSlurper.parseText('{ "myList": [4, 8, 15, 16, 23, 42] }')
.myList
.myList == [4, 8, 15, 16, 23, 42]
The JSON standard supports the following primitive data types: string, number, object, true , false and null . JsonSlurper
converts these JSON types into corresponding Groovy types.
http://docs.groovy-lang.org/latest/html/documentation/ 334/502
1/6/2019 Groovy Language Documentation
jsonSlurper = ()
= jsonSlurper.parseText '''
{ "simple": 123,
"fraction": 123.66,
"exponential": 123e12
}'''
.simple. ==
.fraction. ==
.exponential. ==
As JsonSlurper is returning pure Groovy object instances without any special JSON classes in the back, its usage is transparent.
In fact, JsonSlurper results conform to GPath expressions. GPath is a powerful expression language that is supported by
multiple slurpers for di erent data formats ( XmlSlurper for XML being one example).
For more details please have a look at the section on GPath expressions.
The following table gives an overview of the JSON types and the corresponding Groovy data types:
JSON Groovy
string java.lang.String
object java.util.LinkedHashMap
array java.util.ArrayList
true true
false false
null null
Whenever a value in JSON is null , JsonSlurper supplements it with the Groovy null value. This is in contrast
to other JSON parsers that represent a null value with a library-provided singleton object.
Parser Variants
JsonSlurper comes with a couple of parser implementations. Each parser ts di erent requirements, it could well be that for
certain scenarios the JsonSlurper default parser is not the best bet for all situations. Here is an overview of the shipped parser
implementations:
The JsonParserCharArray parser basically takes a JSON string and operates on the underlying character array. During value
conversion it copies character sub-arrays (a mechanism known as "chopping") and operates on them.
The JsonFastParser is a special variant of the JsonParserCharArray and is the fastest parser. However, it is not the default
parser for a reason. JsonFastParser is a so-called index-overlay parser. During parsing of the given JSON String it tries as
hard as possible to avoid creating new char arrays or String instances. It keeps pointers to the underlying original character
array only. In addition, it defers object creation as late as possible. If parsed maps are put into long-term caches care must be
taken as the map objects might not be created and still consist of pointer to the original char bu er only. However,
JsonFastParser comes with a special chop mode which dices up the char bu er early to keep a small copy of the original
bu er. Recommendation is to use the JsonFastParser for JSON bu ers under 2MB and keeping the long-term cache
restriction in mind.
The JsonParserLax is a special variant of the JsonParserCharArray parser. It has similar performance characteristics as
JsonFastParser but di ers in that it isn’t exclusively relying on the ECMA-404 JSON grammar. For example it allows for
comments, no quote strings etc.
http://docs.groovy-lang.org/latest/html/documentation/ 335/502
1/6/2019 The JsonParserUsingCharacterSource is a special parser
Groovyfor very large
Language les. It uses a technique called "character
Documentation
windowing" to parse large JSON les (large means les over 2MB size in this case) with constant performance characteristics.
The default parser implementation for JsonSlurper is JsonParserCharArray . The JsonParserType enumeration contains
constants for the parser implementations described above:
Implementation Constant
JsonParserCharArray JsonParserType#CHAR_BUFFER
JsonFastParser JsonParserType#INDEX_OVERLAY
JsonParserLax JsonParserType#LAX
JsonParserUsingCharacterSource JsonParserType#CHARACTER_SOURCE
Changing the parser implementation is as easy as setting the JsonParserType with a call to JsonSlurper#setType() .
.myList
.myList == [4, 8, 15, 16, 23, 42]
3.7.2. JsonOutput
JsonOutput is responsible for serialising Groovy objects into JSON strings. It can be seen as companion object to JsonSlurper
(json-userguide.html#json_jsonslurper), being a JSON parser.
JsonOutput comes with overloaded, static toJson methods. Each toJson implementation takes a di erent parameter type.
The static methods can either be used directly or by importing the methods with a static import statement.
JsonOutput does not only support primitive, maps or list data types to be serialized to JSON, it goes further and even has
support for serialising POGOs, that is, plain-old Groovy objects.
{ name }
json == '[{"name":"John"},{"name":"Max"}]'
Customizing Output
If you need control over the serialized output you can use a JsonGenerator . The JsonGenerator.Options builder can be used
to create a customized generator. One or more options can be set on this builder in order to alter the resulting output. When you
are done setting the options simply call the build() method in order to get a fully con gured instance that will generate output
based on the options selected.
http://docs.groovy-lang.org/latest/html/documentation/ 336/502
1/6/2019 Groovy Language Documentation
{
name
title
age
password
dob
URL favoriteUrl
}
generator = . ()
.excludeNulls()
.dateFormat('yyyy@MM')
.excludeFieldsByName('age', 'password')
.excludeFieldsByType(URL)
.build()
generator.toJson(person) == '{"dob":"1984@12","name":"John"}'
A closure can be used to transform a type. These closure converters are registered for a given type and will be called any time that
type or a subtype is encountered. The rst parameter to the closure is an object matching the type for which the converter is
registered and this parameter is required. The closure may take an optional second String parameter and this will be set to the
key name if one is available.
{
name
URL favoriteUrl
}
generator = . ()
.addConverter(URL) { URL u, key ->
(key == 'favoriteUrl') {
u.getHost()
} {
u
}
}
.build()
generator.toJson(person) == '{"favoriteUrl":"groovy-lang.org","name":"John"}'
// First parameter to the converter must match the type for which it is registered
shouldFail( ) {
. ()
.addConverter( ) { cal -> }
}
Formatted Output
As we saw in previous examples, the JSON output is not pretty printed per default. However, the prettyPrint method in
JsonOutput comes to rescue for this task.
http://docs.groovy-lang.org/latest/html/documentation/ 337/502
1/6/2019 Groovy Language Documentation
json = .toJson([name: 'John Doe', age: 42])
.prettyPrint(json) == '''\
{
"name": "John Doe",
"age": 42
}'''.stripIndent()
prettyPrint takes a String as single parameter; therefore, it can be applied on arbitrary JSON String instances, not only the
result of JsonOutput.toJson .
Builders
Another way to create JSON from Groovy is to use JsonBuilder or StreamingJsonBuilder . Both builders provide a DSL which
allows to formulate an object graph which is then converted to JSON.
For more details on builders, have a look at the builders chapter which covers both JsonBuilder and
StreamingJsonBuilder.
Username
Password
The driver class name (which can be derived automatically in some situations)
For our HSQLDB database, the values will be something like that shown in the following table:
Property Value
url jdbc:hsqldb:mem:yourdb
password yourPassword
driver org.hsqldb.jdbcDriver
Consult the documentation for the JDBC driver that you plan to use to determine the correct values for your situation.
The Sql class has a newInstance factory method which takes these parameters. You would typically use it as follows:
Connecting to HSQLDB
http://docs.groovy-lang.org/latest/html/documentation/ 338/502
1/6/2019 Groovy Language Documentation
groovy.sql.
url = 'jdbc:hsqldb:mem:yourDB'
user = 'sa'
password = ''
driver = 'org.hsqldb.jdbcDriver'
sql = .newInstance(url, user, password, driver)
sql.close()
If you don’t want to have to handle resource handling yourself (i.e. call close() manually) then you can use the withInstance
variation as shown here:
groovy.sql.
org.hsqldb.jdbc.
dataSource = (
database: 'jdbc:hsqldb:mem:yourDB', user: 'sa', password: '')
sql = (dataSource)
If you have your own connection pooling, the details will be di erent, e.g. for Apache Commons DBCP:
@Grab('commons-dbcp:commons-dbcp:1.4')
groovy.sql.
org.apache.commons.dbcp.
ds = (driverClassName: "org.hsqldb.jdbcDriver",
url: 'jdbc:hsqldb:mem:yourDB', username: 'sa', password: '')
sql = (ds)
// use then close 'sql' instance ...
@Grab('org.hsqldb:hsqldb:2.3.3')
@GrabConfig(systemClassLoader= )
// create, use, and then close sql instance ...
The @GrabConfig statement is necessary to make sure the system classloader is used. This ensures that the driver classes and
system classes like java.sql.DriverManager are in the same classloader.
Creating a table
There is a variant of this method which takes a GString and another with a list of parameters. There are also other variants with
similar names: executeInsert and executeUpdate . We’ll see examples of these variants in other examples in this section.
Creating/Inserting data
You can use the same execute() statement we saw earlier but to insert a row by using a SQL insert statement as follows:
Inserting a row
You can use a special executeInsert method instead of execute . This will return a list of all keys generated. Both the execute
and executeInsert methods allow you to place '?' placeholders into your SQL string and supply a list of parameters. In this case
a PreparedStatement is used which avoids any risk of SQL injection. The following example illustrates executeInsert using
placeholders and parameters:
In addition, both the execute and executeInsert methods allow you to use GStrings. Any '$' placeholders within the SQL are
assumed to be placeholders. An escaping mechanism exists if you want to supply part of the GString with a variable in a position
which isn’t where normal placeholders go within SQL. See the GroovyDoc for more details. Also, executeInsert allows you to
supply a list of key column names, when multiple keys are returned and you are only interested in some of them. Here is a
fragment illustrating key name speci cation and GStrings:
Inserting a row using executeInsert with a GString and specifying key names
first = 'Guillaume'
= 'Laforge'
myKeyNames = ['ID']
myKeys = sql.executeInsert """
INSERT INTO Author (firstname, lastname)
VALUES (${first}, ${last})
""", myKeyNames
myKeys[0] == [ID: 2]
Reading rows
Reading rows of data from the database is accomplished using one of several available methods: query , eachRow , firstRow
and rows .
Use the query method if you want to iterate through the ResultSet returned by the underlying JDBC API as shown here:
http://docs.groovy-lang.org/latest/html/documentation/ 340/502
1/6/2019 Reading data using query Groovy Language Documentation
rowNum = 0
sql.query('SELECT firstname, lastname FROM Author') { resultSet ->
(resultSet. ()) {
first = resultSet.getString(1)
= resultSet.getString('lastname')
expected[rowNum++] == "$first $last"
}
}
Use the eachRow method if you want a slightly higher-level abstraction which provides a Groovy friendly map-like abstraction for
the ResultSet as shown here:
rowNum = 0
sql.eachRow('SELECT firstname, lastname FROM Author') { row ->
first = row[0]
= row.lastname
expected[rowNum++] == "$first $last"
}
Note that you can use Groovy list-style and map-style notations when accessing the row of data.
Use the firstRow method if you for similar functionality as eachRow but returning only one row of data as shown here:
Use the rows method if you want to process a list of map-like data structures as shown here:
Note that the map-like abstraction has case-insensitive keys (hence we can use 'FIRSTNAME' or ' rstname' as the key) and also
that -ve indices (a standard Groovy feature) works when using an index value (to count column numbers from the right).
You can also use any of the above methods to return scalar values, though typically firstRow is all that is required in such cases.
An example returning the count of rows is shown here:
Updating rows
Updating rows can again be done using the execute() method. Just use a SQL update statement as the argument to the
method. You can insert an author with just a lastname and then update the row to also have a rstname as follows:
Updating a row
There is also a special executeUpdate variant which returns the number of rows updated as a result of executing the SQL. For
example, you can change the lastname of an author as follows:
Using executeUpdate
http://docs.groovy-lang.org/latest/html/documentation/ 341/502
1/6/2019 Groovy Language Documentation
updateSql = "UPDATE Author SET lastname='Pragt' where lastname='Thorvaldsson'"
updateCount = sql.executeUpdate updateSql
updateCount == 1
Deleting rows
The execute method is also used for deleting rows as this example shows:
Deleting rows
A successful transaction
Here the database starts empty and has two rows after successful completion of the operation. Outside the scope of the
transaction, the database is never seen as having just one row.
If something goes wrong, any earlier operations within the withTransaction block are rolled back. We can see that in operation
in the following example where we use database metadata (more details coming up shortly) to nd the maximum allowable size
of the firstname column and then attempt to enter a rstname one larger than that maximum value as shown here:
maxFirstnameLength
metaClosure = { meta -> maxFirstnameLength = meta.getPrecision(1) }
rowClosure = {}
rowCountBefore = sql.firstRow('SELECT COUNT(*) as num FROM Author').num
{
sql.withTransaction {
sql.execute "INSERT INTO Author (firstname) VALUES ('Dierk')"
sql.eachRow "SELECT firstname FROM Author WHERE firstname = 'Dierk'", metaClosure, rowClosure
sql.execute "INSERT INTO Author (firstname) VALUES (?)", 'X' * (maxFirstnameLength + 1)
}
} (ignore) { println ignore.message }
rowCountAfter = sql.firstRow('SELECT COUNT(*) as num FROM Author').num
rowCountBefore == rowCountAfter
Even though the rst sql execute succeeds initially, it will be rolled back and the number of rows will remain the same.
Using batches
When dealing with large volumes of data, particularly when inserting such data, it can be more e cient to chunk the data into
batches. This is done using the withBatch statement as shown in the following example:
http://docs.groovy-lang.org/latest/html/documentation/ 342/502
1/6/2019 Groovy Language Documentation
sql.withBatch(3) { stmt ->
stmt.addBatch "INSERT INTO Author (firstname, lastname) VALUES ('Dierk', 'Koenig')"
stmt.addBatch "INSERT INTO Author (firstname, lastname) VALUES ('Paul', 'King')"
stmt.addBatch "INSERT INTO Author (firstname, lastname) VALUES ('Guillaume', 'Laforge')"
stmt.addBatch "INSERT INTO Author (firstname, lastname) VALUES ('Hamlet', 'D''Arcy')"
stmt.addBatch "INSERT INTO Author (firstname, lastname) VALUES ('Cedric', 'Champeau')"
stmt.addBatch "INSERT INTO Author (firstname, lastname) VALUES ('Erik', 'Pragt')"
stmt.addBatch "INSERT INTO Author (firstname, lastname) VALUES ('Jon', 'Skeet')"
}
After executing these statements, there will be 7 new rows in the database. In fact, they will have been added in batches even
though you can’t easily tell that after that fact. If you want to con rm what is going on under the covers, you can add a little bit of
extra logging into your program. Add the following lines before the withBatch statement:
java.util.logging.*
With this extra logging turned on, and the changes made as per the above comment for the logging.properties le, you should see
output such as:
We should also note, that any combination of SQL statements can be added to the batch. They don’t all have to be inserting a new
row to the same table.
We noted earlier that to avoid SQL injection, we encourage you to use prepared statements, this is achieved using the variants of
methods which take GStrings or a list of extra parameters. Prepared statements can be used in combination with batches as
shown in the following example:
This provides a much safer option if the data could come from a user such as via a script or a web form. Of course, given that a
prepared statement is being used, you are limited to a batch of the same SQL operation (insert in our example) to the one table.
Performing pagination
When presenting large tables of data to a user, it is often convenient to present information a page at a time. Many of Groovy’s
SQL retrieval methods have extra parameters which can be used to select a particular page of interest. The starting position and
page size are speci ed as integers as shown in the following example using rows :
http://docs.groovy-lang.org/latest/html/documentation/ 343/502
1/6/2019 Retrieving pages of data Groovy Language Documentation
Fetching metadata
JDBC metadata can be retrieved in numerous ways. Perhaps the most basic approach is to extract the metadata from any row as
shown in the following example which examines the tablename, column names and column type names:
And another slight variant to the previous example, this time also looking at the column label:
sql.eachRow("SELECT firstname AS first FROM Author WHERE firstname = 'Dierk'") { row ->
md = row.getMetaData()
md.getColumnName(1) == 'FIRSTNAME'
md.getColumnLabel(1) == 'FIRST'
}
Accessing metadata is quite common, so Groovy also provides variants to many of its methods that let you supply a closure that
will be called once with the row metadata in addition to the normal row closure which is called for each row. The following
example illustrates the two closure variant for eachRow :
Note that our SQL query will only return one row, so we could have equally used firstRow for the previous example.
Finally, JDBC also provides metadata per connection (not just for rows). You can also access such metadata from Groovy as shown
in this example:
md = sql.connection.metaData
md.driverName == 'HSQL Database Engine Driver'
md.databaseProductVersion == '2.3.3'
['JDBCMajorVersion', 'JDBCMinorVersion'].collect{ md[it] } == [4, 0]
md.stringFunctions.tokenize(',').contains('CONCAT')
rs = md.getTables( , , 'AUTH%', )
rs. ()
rs.getString('TABLE_NAME') == 'AUTHOR'
Consult the JavaDoc for your driver to nd out what metadata information is available for you to access.
http://docs.groovy-lang.org/latest/html/documentation/ 344/502
1/6/2019 variants but instead of having a list of ? placeholders followed
GroovybyLanguage
a list of parameters, you have one or more placeholders having
Documentation
the form :propName or ?.propName and a single map, named arguments or a domain object as the parameter. The map or
domain object should have a property named propName corresponding to each supplied placeholder.
sql.execute "INSERT INTO Author (firstname, lastname) VALUES (:first, :last)", first: 'Dierk',
: 'Koenig'
sql.execute "INSERT INTO Author (firstname, lastname) VALUES (?.first, ?.last)", first: 'Jon',
: 'Skeet'
If the information you need to supply is spread across multiple maps or domain objects you can use the question mark form with
an additional ordinal index as shown here:
Named-ordinal parameters
{ first, }
pogo = (first: 'Paul', : 'McCartney')
map = [lion: 'King']
sql.execute "INSERT INTO Author (firstname, lastname) VALUES (?1.first, ?2.lion)", pogo, map
Stored procedures
The exact syntax for creating a stored procedure or function varies slightly between di erent databases. For the HSQLDB
database we are using, we can create a stored function which returns the initials of all authors in a table as follows:
sql.execute """
CREATE FUNCTION SELECT_AUTHOR_INITIALS()
RETURNS TABLE (firstInitial VARCHAR(1), lastInitial VARCHAR(1))
READS SQL DATA
RETURN TABLE (
SELECT LEFT(Author.firstname, 1) as firstInitial, LEFT(Author.lastname, 1) as lastInitial
FROM Author
)
"""
We can use a SQL CALL statement to invoke the function using Groovy’s normal SQL retrieval methods. Here is an example using
eachRow .
result = []
sql.eachRow('CALL SELECT_AUTHOR_INITIALS()') {
result << "$it.firstInitial$it.lastInitial"
}
result == ['DK', 'JS', 'GL']
Here is the code for creating another stored function, this one taking the lastname as a parameter:
http://docs.groovy-lang.org/latest/html/documentation/ 345/502
1/6/2019 Groovy Language Documentation
sql.execute """
CREATE FUNCTION FULL_NAME (p_lastname VARCHAR(64))
RETURNS VARCHAR(100)
READS SQL DATA
BEGIN ATOMIC
DECLARE ans VARCHAR(100);
SELECT CONCAT(firstname, ' ', lastname) INTO ans
FROM Author WHERE lastname = p_lastname;
RETURN ans;
END
"""
We can use the placeholder syntax to specify where the parameter belongs and note the special placeholder position to indicate
the result:
sql.execute """
CREATE PROCEDURE CONCAT_NAME (OUT fullname VARCHAR(100),
IN first VARCHAR(50), IN last VARCHAR(50))
BEGIN ATOMIC
SET fullname = CONCAT(first, ' ', last);
END
"""
To use the CONCAT_NAME stored procedure parameter, we make use of a special call method. Any input parameters are simply
provided as parameters to the method call. For output parameters, the resulting type must be speci ed as shown here:
groovy.util.XmlParser
groovy.util.XmlSlurper
Both have the same approach to parse an xml. Both come with a bunch of overloaded parse methods plus some special methods
such as parseText , parseFile and others. For the next example we will use the parseText method. It parses a XML String and
recursively converts it to a list or map of objects.
XmlSlurper
http://docs.groovy-lang.org/latest/html/documentation/ 346/502
1/6/2019 Groovy Language Documentation
text = '''
<list>
<technology>
<name>Groovy</name>
</technology>
</list>
'''
list = ().parseText(text) 1
list groovy.util.slurpersupport. 2
list.technology.name == 'Groovy' 3
XmlParser
text = '''
<list>
<technology>
<name>Groovy</name>
</technology>
</list>
'''
list = ().parseText(text) 1
list groovy.util. 2
list.technology.name.text() == 'Groovy' 3
Both are based on SAX so they both are low memory footprint
XmlSlurper evaluates the structure lazily. So if you update the xml you’ll have to evaluate the whole tree again.
If you want to transform an existing document to another then XmlSlurper will be the choice
If you want to update and read at the same time then XmlParser is the choice.
The rationale behind this is that every time you create a node with XmlSlurper it won’t be available until you parse the
document again with another XmlSlurper instance. Need to read just a few nodes XmlSlurper is for you ".
If you just have to read a few nodes XmlSlurper should be your choice, since it will not have to create a complete structure
in memory"
http://docs.groovy-lang.org/latest/html/documentation/ 347/502
1/6/2019 In general both classes perform similar way. Even the wayGroovy
of using GPath expressions
Language with them are the same (both use
Documentation
breadthFirst() and depthFirst() expressions). So I guess it depends on the write/read frequency.
DOMCategory
There is another way of parsing XML documents with Groovy with the used of groovy.xml.dom.DOMCategory which is a category
class which adds GPath style operations to Java’s DOM classes.
Java has in-built support for DOM processing of XML using classes representing the various parts of XML
documents, e.g. Document , Element , NodeList , Attr etc. For more information about these classes, refer to
the respective JavaDocs.
CAR_RECORDS = '''
<records>
<car name='HSV ' make=' ' year='2006'>
<country>Australia</country>
<record type='speed'>Production Pickup Truck with speed of 271kph</record>
</car>
<car name='P50' make=' ' year='1962'>
<country>Isle of Man</country>
<record type='size'>Smallest Street-Legal Car at 99cm wide and 59 kg in weight</record>
</car>
<car name=' ' make=' ' year='1931'>
<country>France</country>
<record type='price'>Most Valuable Car at $15 million</record>
</car>
</records>
'''
reader = (CAR_RECORDS)
doc = .parse(reader) 1
records = doc.documentElement
( ) { 2
records.car.size() == 3
}
3.9.2. GPath
The most common way of querying XML in Groovy is using GPath :
GPath is a path expression language integrated into Groovy which allows parts of nested structured data to be identi ed. In this
sense, it has similar aims and scope as XPath does for XML. The two main places where you use GPath expressions is when
dealing with nested POJOs or when dealing with XML
It is similar to XPath (http://en.wikipedia.org/wiki/XPath) expressions and you can use it not only with XML but also with POJO
classes. As an example, you can specify a path to an object or element of interest:
a.b.c → for XML, yields all the <c> elements inside <b> inside <a>
a.b.c → all POJOs, yields the <c> properties for all the <b> properties of <a> (sort of like a.getB().getC() in JavaBeans)
books = '''
<response version-api="2.0">
<value>
<books>
<book available="20" id="1">
<title>Don Xijote</title>
<author id="1">Manuel De Cervantes</author>
</book>
<book available="14" id="2">
<title>Catcher in the Rye</title>
<author id="2">JD Salinger</author>
</book>
<book available="13" id="3">
<title>Alice in Wonderland</title>
<author id="3">Lewis Carroll</author>
</book>
<book available="5" id="4">
<title>Don Xijote</title>
<author id="4">Manuel De Cervantes</author>
</book>
</books>
</value>
</response>
'''
response = ().parseText(books)
authorResult = response.value.books.book[0].author
First we parse the document with XmlSlurper and the we have to consider the returning value as the root of the XML document,
so in this case is "response".
That’s why we start traversing the document from response and then value.books.book[0].author . Note that in XPath the
node arrays starts in [1] instead of [0], but because GPath is Java-based it begins at index 0.
In the end we’ll have the instance of the author node and because we wanted the text inside that node we should be calling the
text() method. The author node is an instance of GPathResult type and text() a method giving us the content of that
node as a String.
When using GPath with an xml parsed with XmlSlurper we’ll have as a result a GPathResult object. GPathResult has many
other convenient methods to convert the text inside a node to any other type such as:
toInteger()
toFloat()
toBigInteger()
If we were using a XML parsed with XmlParser we could be dealing with instances of type Node . But still all the actions applied
to GPathResult in these examples could be applied to a Node as well. Creators of both parsers took into account GPath
compatibility.
Next step is to get the some values from a given node’s attribute. In the following sample we want to get the rst book’s author’s
id. We’ll be using two di erent approaches. Let’s see the code rst:
http://docs.groovy-lang.org/latest/html/documentation/ 349/502
1/6/2019 Getting an attribute’s value Groovy Language Documentation
response = ().parseText(books)
book = response.value.books.book[0] 1
bookAuthorId1 = book.@id 2
bookAuthorId2 = book['@id'] 3
bookAuthorId1 == '1' 4
bookAuthorId1.toInteger() == 1 5
bookAuthorId1 == bookAuthorId2
As you can see there are two types of notations to get attributes, the
// : Look everywhere
More or less we have their counterparts in GPath with the shortcuts * (aka children() ) and ** (aka depthFirst() ).
The rst example shows a simple use of * , which only iterates over the direct children of the node.
Using *
response = ().parseText(books)
This test searches for any child nodes of the "books" node matching the given condition. In a bit more detail, the expression says:
Look for any node with a tag name equal to 'book' having an id with a value of '2' directly under the 'books' node.
This operation roughly corresponds to the breadthFirst() method, except that it only stops at one level instead of continuing
to the inner levels.
What if we would like to look for a given value without having to know exactly where it is. Let’s say that the only thing we know is
the id of the author "Lewis Carroll" . How are we going to be able to nd that book? Using ** is the solution:
Using **
http://docs.groovy-lang.org/latest/html/documentation/ 350/502
1/6/2019 Groovy Language Documentation
response = ().parseText(books)
bookId == 3
** is the same as looking for something everywhere in the tree from this point down. In this case, we’ve used the method
find(Closure cl) to nd just the rst occurrence.
What if we want to collect all book’s titles? That’s easy, just use findAll :
response = ().parseText(books)
titles.size() == 4
In the last two examples, ** is used as a shortcut for the depthFirst() method. It goes as far down the tree as it can while
navigating down the tree from a given node. The breadthFirst() method nishes o all nodes on a given level before
traversing down to the next level.
The following example shows the di erence between these two methods:
depthFirst() vs .breadthFirst
response = ().parseText(books)
nodeName = { node -> node.name() }
withId2or3 = { node -> node.@id [2, 3] }
In this example, we search for any nodes with an id attribute with value 2 or 3. There are both book and author nodes that
match that criteria. The di erent traversal orders will nd the same nodes in each case but in di erent orders corresponding to
how the tree was traversed.
It is worth mentioning again that there are some useful methods converting a node’s value to an integer, oat, etc. Those methods
could be convenient when doing comparisons like this:
helpers
response = ().parseText(books)
titles = response.value.books.book.findAll{book->
/* You can use toInteger() over the GPathResult object */
[email protected]() > 2
}*.title
titles.size() == 2
In this case the number 2 has been hardcoded but imagine that value could have come from any other source (database… etc.).
groovy.xml.MarkupBuilder
groovy.xml.StreamingMarkupBuilder
MarkupBuilder
http://docs.groovy-lang.org/latest/html/documentation/ 351/502
1/6/2019 Here is an example of using Groovy’s MarkupBuilder to create a new
Groovy XML Documentation
Language le:
writer = ()
xml = (writer) 1
xml.records() { 2
car(name:'HSV Maloo', make:'Holden', year:2006) {
country('Australia')
record(type:'speed', 'Production Pickup Truck with speed of 271kph')
}
car(name:'Royale', make:'Bugatti', year:1931) {
country('France')
record(type:'price', 'Most Valuable Car at $15 million')
}
}
records = ().parseText(writer.toString()) 3
xmlWriter = () 2
xmlMarkup = (xmlWriter)
xmlMarkup.movie("the godfather") 3
xmlString == xmlWriter.toString() 4
xmlWriter = ()
xmlMarkup = (xmlWriter)
xmlString == xmlWriter.toString()
This time in order to create both attributes and node content you can create as many map entries as you like and nally add
1
a value to set the node’s content
The value could be any Object , the value will be serialized to its String representation.
http://docs.groovy-lang.org/latest/html/documentation/ 352/502
1/6/2019 Groovy Language Documentation
xmlWriter = ()
xmlMarkup = (xmlWriter)
xmlMarkup.movie(id: 2) { 1
name("the godfather")
}
movie = ().parseText(xmlWriter.toString())
movie.@id == 2
movie.name.text() == 'the godfather'
A closure represents the children elements of a given node. Notice this time instead of using a String for the attribute we’re
1
using a number.
Sometimes you may want to use a speci c namespace in your xml documents:
Namespace aware
xmlWriter = ()
xmlMarkup = (xmlWriter)
xmlMarkup
.'x:movies'('xmlns:x':'http://www.groovy-lang.org') { 1
movies =
() 2
.parseText(xmlWriter.toString())
.declareNamespace(x:'http://www.groovy-lang.org')
movies.'x:movie'. ().@id == 2
movies.'x:movie'. ().text() == 'ronin'
What about having some more meaningful example. We may want to generate more elements, to have some logic when creating
our XML:
Mix code
xmlWriter = ()
xmlMarkup = (xmlWriter)
xmlMarkup
.'x:movies'('xmlns:x':'http://www.groovy-lang.org') {
(1..3).each { n -> 1
'x:movie'(id: n, "the godfather $n")
(n % 2 == 0) { 2
'x:movie'(id: n, "the godfather $n (Extended)")
}
}
}
movies =
()
.parseText(xmlWriter.toString())
.declareNamespace(x:'http://www.groovy-lang.org')
movies.'x:movie'.size() == 4
movies.'x:movie'*.text().every { name -> name.startsWith('the')}
Of course the instance of a builder can be passed as a parameter to refactor/modularize your code:
Mix code
xmlWriter = ()
xmlMarkup = (xmlWriter)
builder
}
xmlMarkup.'x:movies'('xmlns:x':'http://www.groovy-lang.org') {
buildMovieList(xmlMarkup) 2
}
movies =
()
.parseText(xmlWriter.toString())
.declareNamespace(x:'http://www.groovy-lang.org')
movies.'x:movie'.size() == 4
movies.'x:movie'*.text().every { name -> name.startsWith('the')}
1 In this case we’ve created a Closure to handle the creation of a list of movies
2 Just using the buildMovieList function when necessary
StreamingMarkupBuilder
The class groovy.xml.StreamingMarkupBuilder is a builder class for creating XML markup. This implementation uses a
groovy.xml.streamingmarkupsupport.StreamingMarkupWriter to handle output.
Using StreamingMarkupBuilder
xml = ().bind { 1
records {
car(name:'HSV Maloo', make:'Holden', year:2006) { 2
country('Australia')
record(type:'speed', 'Production Pickup Truck with speed of 271kph')
}
car(name:'P50', make:'Peel', year:1962) {
country('Isle of Man')
record(type:'size', 'Smallest Street-Legal Car at 99cm wide and 59 kg in weight')
}
car(name:'Royale', make:'Bugatti', year:1931) {
country('France')
record(type:'price', 'Most Valuable Car at $15 million')
}
}
}
records = ().parseText(xml.toString()) 3
records.car.size() == 3
records.car.find { it.@name == 'P50' }.country.text() == 'Isle of Man'
Note that StreamingMarkupBuilder.bind returns a Writable instance that may be used to stream the markup to a
1
Writer
http://docs.groovy-lang.org/latest/html/documentation/ 354/502
1/6/2019 2 Groovy
We’re capturing the output in a String to parse it again Language
an check Documentation
the structure of the generated XML with XmlSlurper .
MarkupBuilderHelper
The groovy.xml.MarkupBuilderHelper is, as its name re ects, a helper for groovy.xml.MarkupBuilder .
This helper normally can be accessed from within an instance of class groovy.xml.MarkupBuilder or an instance of
groovy.xml.StreamingMarkupBuilder .
This helper could be handy in situations when you may want to:
Print data in the body of the current tag, escaping XML entities
In both MarkupBuilder and StreamingMarkupBuilder this helper is accessed by the property mkp :
xmlWriter = ()
xmlMarkup = (xmlWriter).rules {
mkp.comment('THIS IS THE MAIN RULE') 1
rule(sentence: mkp. ('3 > n')) 2
}
Here is another example to show the use of mkp property accessible from within the bind method scope when using
StreamingMarkupBuilder :
xml = ().bind {
records {
car(name: mkp. ('3 < 5')) 1
car(name: mkp.yieldUnescaped('1 < 3')) 2
}
}
1 If we want to generate a escaped value for the name attribute with mkp.yield
2 Checking the values later on with XmlSlurper
DOMToGroovy
Suppose we have an existing XML document and we want to automate generation of the markup without having to type it all in?
We just need to use org.codehaus.groovy.tools.xml.DOMToGroovy as shown in the following example:
http://docs.groovy-lang.org/latest/html/documentation/ 355/502
1/6/2019 Groovy Language Documentation
songs = """
<songs>
<song>
<title>Here I go</title>
<band>Whitesnake</band>
</song>
</songs>
"""
builder =
javax.xml.parsers. .newInstance().newDocumentBuilder()
inputStream = (songs.bytes)
document = builder.parse(inputStream)
output = ()
converter = ( (output)) 1
converter. (document) 2
xmlRecovered =
()
.evaluate("""
def writer = new StringWriter()
def builder = new groovy.xml.MarkupBuilder(writer)
builder.${output}
return writer.toString()
""") 3
xml = """
<response version-api="2.0">
<value>
<books>
<book id="2">
<title>Don Xijote</title>
<author id="1">Manuel De Cervantes</author>
</book>
</books>
</value>
</response>
"""
Adding nodes
The main di erence between XmlSlurper and XmlParser is that when former creates the nodes they won’t be available until
the document’s been evaluated again, so you should parse the transformed document again in order to be able to see the new
nodes. So keep that in mind when choosing any of both approaches.
If you needed to see a node right after creating it then XmlParser should be your choice, but if you’re planning to do many
changes to the XML and send the result to another process maybe XmlSlurper would be more e cient.
You can’t create a new node directly using the XmlSlurper instance, but you can with XmlParser . The way of creating a new
node from XmlParser is through its method createNode(..)
http://docs.groovy-lang.org/latest/html/documentation/ 356/502
1/6/2019 Groovy Language Documentation
parser = ()
response = parser.parseText(xml)
numberOfResults = parser.createNode(
response,
("numberOfResults"),
[:]
)
numberOfResults.value = "1"
response.numberOfResults.text() == "1"
The quali ed name for the tag (In this case we only use the local part without any namespace). We’re using an instance of
groovy.xml.QName
Anyway you won’t normally be creating a node from the parser instance but from the parsed XML instance. That is from a Node
or a GPathResult instance.
Take a look at the next example. We are parsing the xml with XmlParser and then creating a new node from the parsed
document’s instance (Notice the method here is slightly di erent in the way it receives the parameters):
parser = ()
response = parser.parseText(xml)
response.appendNode(
("numberOfResults"),
[:],
"1"
)
response.numberOfResults.text() == "1"
response = ().parseText(xml)
newNode = response.value.books.book[0]
newNode.name() == "book"
newNode.@id == "3"
newNode.title.text() == "To Kill a Mockingbird"
newNode.author.text() == "Harper Lee"
[email protected]() == "3"
When using replaceNode() the closure we pass as parameter should follow the same rules as if we were using
groovy.xml.MarkupBuilder :
/* That mkp is a special namespace used to escape away from the normal building mode
of the builder and get access to helper markup methods
'yield', 'pi', 'comment', 'out', 'namespaces', 'xmlDeclaration' and
'yieldUnescaped' */
result = ().bind { mkp. response }.toString()
changedResponse = ().parseText(result)
Notice how using XmlSlurper we have to parse the transformed document again in order to nd the created nodes. In this
particular example could be a little bit annoying isn’t it?
Finally both parsers also use the same approach for adding a new attribute to a given attribute. This time again the di erence is
whether you want the new nodes to be available right away or not. First XmlParser :
parser = ()
response = parser.parseText(xml)
response.@numberOfResults = "1"
response.@numberOfResults == "1"
And XmlSlurper :
response = ().parseText(books)
response.@numberOfResults = "2"
response.@numberOfResults == "2"
When using XmlSlurper , adding a new attribute does not require you to perform a new evaluation.
Printing XML
XmlUtil
Sometimes is useful to get not only the value of a given node but the node itself (for instance to add this node to another XML).
For that you can use groovy.xml.XmlUtil class. It has several static methods to serialize the xml fragment from several type of
sources (Node, GPathResult, String…)
response = ().parseText(xml)
nodeToSerialize = response.'**'.find {it.name() == 'author'}
nodeAsText = .serialize(nodeToSerialize)
nodeAsText ==
.serialize('<?xml version="1.0" encoding="UTF-8"?><author id="1">Manuel De
Cervantes</author>')
Executes a series of Groovy statements from Apache Ant (http://ant.apache.org/). Statements can either be read in from a text le
using the src attribute or from between the enclosing Groovy tags.
name="groovy"
classname="org.codehaus.groovy.ant.Groovy"
classpathref="my.classpath"
src="..." otherAttributes="..."
Or this:
...
You might need to use the contextClassLoader attribute (see below) if any of your modules load services via the classpath, e.g.
groovy-json .
src File containing Groovy statements. The directory containing Yes, unless statements
the le is added to the classpath. enclosed within tags
con gScript Sets the con guration script for the groovy compiler No
con guration.
<classpath>
Groovy’s classpath attribute is a PATH like structure and can also be set via a nested classpath element.
<arg>
Arguments can be set via one or more nested <arg> elements using the standard Ant command line conventions
(http://ant.apache.org/manual/using.html#arg).
Name Description
ant an instance of AntBuilder that knows about the current ant project
3.11.5. Examples
Hello world, version 1:
project.references.found.each {
println it.name
}
Run a script:
src="/some/directory/some/file.groovy"
location="/my/groovy/classes/directory"
Find all Builder classes having an org.* package within a directory of jars:
name="local.target" value="C:/Projects/GroovyExamples"
import java.util.jar.JarFile
def classes = []
def resourceNamePattern = /org\/.*\/.*Builder.class/
def jarNamePattern = /.*(beta|commons).*jar$/
message='${builder-classes}'
org/apache/commons/cli/ . org/apache/commons/cli/ .
org/codehaus/groovy/tools/groovydoc/ .
org/custommonkey/xmlunit/ .
org/custommonkey/xmlunit/ .
import java.util.jar.JarFile
def resourceNamePattern = /org\/.*\/.*Builder.class/
def candidates = ant.fileScanner {
fileset(dir: '${local.target}/lib') {
include(name: '*beta*.jar')
include(name: '*commons*.jar')
}
}
def classes = candidates.collect {
new JarFile(it).entries().collect { it.name }.findAll {
it ==~ resourceNamePattern
}
}.flatten()
properties["builder-classes"] = classes.join(' ')
http://docs.groovy-lang.org/latest/html/documentation/ 361/502
1/6/2019 Groovy Language Documentation
<?xml version="1.0" encoding="UTF-8"?>
name="SOAP example" default="main" basedir="."
environment="env"
name="celsius" value="0"
name="main"
name="groovy" classname="org.codehaus.groovy.ant.Groovy"
dir="${env.GROOVY_HOME}" includes="lib/groovy-*.jar,lib/ivy*.jar"
@Grab('org.codehaus.groovy.modules:groovyws:0.5.1')
import groovyx.net.ws.WSClient
def url = 'http://www.w3schools.com/webservices/tempconvert.asmx?WSDL'
def proxy = new WSClient(url, this.class.classLoader)
proxy.initialize()
ant.echo "I'm freezing at ${properties.celsius} degrees Celsius"
properties.result = proxy.CelsiusToFahrenheit(properties.celsius)
target="results"
name="results"
message="I'm freezing at ${result} degrees Fahrenheit"
Which will output the following (along with some informational messages):
main:
...
[echo] I'm freezing at 0 degrees Celsius
results:
[echo] I'm freezing at 32 degrees
BUILD SUCCESSFUL
Setting arguments:
name="run"
line="1 2 3"
value="4 5"
println args.size()
println args[2]
args.each{ ant.echo(message:it) }
Output:
: build.xml
run:
[groovy] 4
[groovy] 3
[echo] 1
[echo] 2
[echo] 3
[echo] 4 5
BUILD SUCCESSFUL
StreamingTemplateEngine - functionally equivalent to SimpleTemplateEngine , but can handle strings larger than 64k
GStringTemplateEngine - stores the template as writeable closures (useful for streaming scenarios)
XmlTemplateEngine - works well when the template and output are valid XML
3.12.3. SimpleTemplateEngine
Shown here is the SimpleTemplateEngine that allows you to use JSP-like scriptlets (see example below), script, and EL
expressions in your template in order to generate parametrized text. Here is an example of using the system:
text = 'Dear "$firstname $lastname",\nSo nice to meet you in <% print city %>.\nSee you in
${month},\n${signed}'
engine = groovy.text. ()
= engine.createTemplate(text).make(binding)
result = 'Dear "Sam Pullara",\nSo nice to meet you in San Francisco.\nSee you in
December,\nGroovy-Dev'
result == .toString()
While it is generally not deemed good practice to mix processing logic in your template (or view), sometimes very simple logic can
be useful. E.g. in the example above, we could change this:
$firstname
to this (assuming we have set up a static import for capitalize inside the template):
${firstname.capitalize()}
or this:
to this:
http://docs.groovy-lang.org/latest/html/documentation/ 363/502
1/6/2019 Groovy Language Documentation
<% city == "New York" ? "\\" \\"" : city %>
\\n
in any GString expression or scriptlet 'code' that appears inside a Groovy script. A normal “\n” is ne within the static template text
itself or if the entire template itself is in an external template le. Similarly, to represent an actual backslash in your text you would
need
\\\\
in an external le or
\\\\
in any GString expression or scriptlet 'code'. (Note: the necessity to have this extra slash may go away in a future version of
Groovy if we can nd an easy way to support such a change.)
3.12.4. StreamingTemplateEngine
The StreamingTemplateEngine engine is functionally equivalent to the SimpleTemplateEngine , but creates the template using
writable closures making it more scalable for large templates. Speci cally this template engine can handle strings larger than 64k.
It uses JSP style <% %> script and <%= %> expression syntax or GString style expressions. The variable 'out' is bound to the writer
that the template is being written to.
Frequently, the template source will be a le but here we show a simple example providing the template as a string:
text = '''\
Dear <% out.print firstname %> ${lastname},
= groovy.text. ().createTemplate(text)
binding = [
firstname : "Grace",
lastname : "Hopper",
accepted : ,
title : 'Groovy for COBOL programmers'
]
response = .make(binding)
3.12.5. GStringTemplateEngine
As an example of using the GStringTemplateEngine , here is the example above done again (with a few changes to show some
other options). First we will store the template in a le this time:
test.template
http://docs.groovy-lang.org/latest/html/documentation/ 364/502
1/6/2019 Groovy Language Documentation
"$firstname $lastname",
nice to meet you <% << (city == "New York" ? "\\" \\"" : city) %>.
you ${month},
${ }
Note that we used out instead of print to support the streaming nature of GStringTemplateEngine . Because we have the
template in a separate le, there is no need to escape the backslashes. Here is how we call it:
f = ('test.template')
engine = groovy.text. ()
= engine.createTemplate(f).make(binding)
println .toString()
3.12.6. XmlTemplateEngine
XmlTemplateEngine for use in templating scenarios where both the template source and the expected output are intended to be
XML. Templates may use the normal ${expression} and $variable notations to insert an arbitrary expression into the
template. In addition, support is also provided for special tags: <gsp:scriptlet> (for inserting code fragments) and
<gsp:expression> (for code fragments which produce output).
Comments and processing instructions will be removed as part of processing and special XML characters such as < , > , " and '
will be escaped using the respective XML notation. The output will also be indented using standard XML pretty printing.
The xmlns namespace de nition for gsp: tags will be removed but other namespace de nitions will be preserved (but may change
to an equivalent position within the XML tree).
Normally, the template source will be in a le but here is a simple example providing the XML template as a string:
type='letter'
Dearest
xmlns:foo='baz'
Jochen "blackdrag" Theodorou
http://docs.groovy-lang.org/latest/html/documentation/ 365/502
1/6/2019 This template engine is a template engine primarily aimedGroovy
at generating
LanguageXML-like markup (XML, XHTML, HTML5, …), but that can
Documentation
be used to generate any text based content. Unlike traditional template engines, this one relies on a DSL that uses the builder
syntax. Here is a sample template:
xmlDeclaration()
cars {
cars.each {
car(make: it.make, model: it.model)
}
}
model = [cars: [ (make: 'Peugeot', model: '508'), (make: 'Toyota', model: 'Prius')]]
<?xml version='1.0'?>
make='Peugeot' model='508' make='Toyota' model='Prius'
fast rendering
includes
internationalization support
fragments/layouts
Basics
Templates consist of Groovy code. Let’s explore the rst example more thoroughly:
xmlDeclaration() 1
cars { 2
cars.each { 3
} 5
As you can see, regular Groovy code can be used in the template. Here, we are calling each on a list (retrieved from the model),
allowing us to render one car tag per entry.
http://docs.groovy-lang.org/latest/html/documentation/ 366/502
1/6/2019 Groovy Language Documentation
yieldUnescaped '<!DOCTYPE html>' 1
html(lang:'en') { 2
head { 3
title('My page') 5
} 6
body { 7
} 9
} 10
With some con guration, you can have the output pretty printed, with newlines and indent automatically added.
Support methods
In the previous example, the doctype declaration was rendered using the yieldUnescaped method. We have also seen the
xmlDeclaration method. The template engine provides several support methods that will help you render contents
appropriately:
Output:
Output:
http://docs.groovy-lang.org/latest/html/documentation/ 367/502
1/6/2019 Groovy Language Documentation
Method Description Example
Output:
<?xml version='1.0'?>
If TemplateConfiguration#getDeclarationEncoding
is not null:
Output:
Output:
Output:
text
text on new line
pi("xml-stylesheet":[href:"mystyle.css",
type:"text/css"])
Output:
<?xml-stylesheet href='mystyle.css'
type='text/css'?>
http://docs.groovy-lang.org/latest/html/documentation/ 368/502
1/6/2019 Groovy Language Documentation
Method Description Example
Output:
Includes
The MarkupTemplateEngine supports inclusion of contents from another le. Included contents may be:
another template
raw contents
contents to be escaped
include : 'other_template.tpl'
Including a le as raw contents, without escaping it, can be done like this:
Eventually, inclusion of text that should be escaped before rendering can be done using:
Calling those methods instead of the include xxx: syntax can be useful if the name of the le to be included is dynamic (stored
in a variable for example). Files to be included (independently of their type, template or text) are found on classpath. This is one of
the reasons why the MarkupTemplateEngine takes an optional ClassLoader as constructor argument (the other reason being
that you can include code referencing other classes in a template).
If you don’t want your templates to be on classpath, the MarkupTemplateEngine accepts a convenient constructor that lets you
de ne the directory where templates are to be found.
Fragments
Fragments are nested templates. They can be used to provide improved composition in a single template. A fragment consists of a
string, the inner template, and a model, used to render this template. Consider the following template:
ul {
pages.each {
fragment "li(line)", line:it
}
}
The fragment element creates a nested template, and renders it with a model which is speci c to this template. Here, we have
the li(line) fragment, where line is bound to it . Since it corresponds to the iteration of pages , we will generate a single
li element for each page in our model:
http://docs.groovy-lang.org/latest/html/documentation/ 369/502
1/6/2019 Groovy Language Documentation
Page 1 Page 2
Fragments are interesting to factorize template elements. They come at the price of the compilation of a fragment per template,
and they cannot be externalized.
Layouts
Layouts, unlike fragments, refer to other templates. They can be used to compose templates and share common structures. This
is often interesting if you have, for example, a common HTML page setup, and that you only want to replace the body. This can be
done easily with a layout. First of all, you need to create a layout template:
layout-main.tpl
html {
head {
title(title) 1
}
body {
bodyContents() 2
}
}
layout 'layout-main.tpl', 1
As you can see, bodyContents will be rendered inside the layout, thanks to the bodyContents() call in the layout le. As a
result, the template will be rendered as this:
The call to the contents method is used to tell the template engine that the block of code is in fact a speci cation of a template,
instead of a helper function to be rendered directly. If you don’t add contents before your speci cation, then the contents would
be rendered, but you would also see a random string generated, corresponding to the result value of the block.
Layouts are a powerful way to share common elements across multiple templates, without having to rewrite everything or use
includes.
Layouts use, by default, a model which is independent from the model of the page where they are used. It is however possible to
make them inherit from the parent model. Imagine that the model is de ned like this:
layout 'layout-main.tpl', , 1
then it is not necessary to pass the title value to the layout as in the previous example. The result will be:
http://docs.groovy-lang.org/latest/html/documentation/ 370/502
1/6/2019 Groovy Language Documentation
Title from main model This is the body
layout 'layout-main.tpl', , 1
Rendering contents
config = (); 1
engine = (config); 2
output = template.make(model); 5
output.writeTo(writer); 6
= engine.createTemplateByPath("main.tpl");
output = .make(model);
output.writeTo(writer);
http://docs.groovy-lang.org/latest/html/documentation/ 371/502
1/6/2019 Groovy Language Documentation
Option Default value Description Example
Output:
Output:
If expandEmptyElements is true:
Output:
Output:
attr='value'
If useDoubleQuotes is true:
Output:
attr="value"
http://docs.groovy-lang.org/latest/html/documentation/ 372/502
1/6/2019 Groovy Language Documentation
Option Default value Description Example
If newLineString='BAR' :
Output:
autoIndentString four (4) spaces The string to be See the auto formatting section
used as indent.
baseTemplateClass groovy.text.markup.BaseTemplate Sets the super See the custom templates section
class of compiled
templates. This
can be used to
provide
application
speci c
templates.
locale Default locale Sets the default See the internationalization section
locale for
templates.
Once the template engine has been created, it is unsafe to change the con guration.
Automatic formatting
By default, the template engine will render output without any speci c formatting. Some con guration options can improve the
situation:
autoNewLine is responsible for automatically inserting new lines based on the original formatting of the template source
In general, it is recommended to set both autoIndent and autoNewLine to true if you want human-readable, pretty printed,
output:
http://docs.groovy-lang.org/latest/html/documentation/ 373/502
1/6/2019 Groovy Language Documentation
config.setAutoNewLine( );
config.setAutoIndent( );
html {
head {
title('Title')
}
}
Title
We can slightly change the template so that the title instruction is found on the same line as the head one:
html {
head { title('Title')
}
}
Title
New lines are only inserted where curly braces for tags are found, and the insertion corresponds to where the nested content is
found. This means that tags in the body of another tag will not trigger new lines unless they use curly braces themselves:
html {
head {
meta(attr:'value') 1
title('Title') 2
newLine() 3
meta(attr:'value2') 4
}
}
1 a new line is inserted because meta is not on the same line as head
2 no new line is inserted, because we’re on the same depth as the previous tag
3 we can force rendering of a new line by explicitly calling newLine
4 and this tag will be rendered on a separate line
attr='value' Title
attr='value2'
http://docs.groovy-lang.org/latest/html/documentation/ 374/502
1/6/2019 By default, the renderer uses four(4) spaces as indent, butGroovy
you can change itDocumentation
Language by setting the
TemplateConfiguration#autoIndentString property.
Automatic escaping
By default, contents which is read from the model is rendered as is. If this contents comes from user input, it can be sensible, and
you might want to escape it by default, for example to avoid XSS injection. For that, the template con guration provides an option
which will automatically escape objects from the model, as long as they inherit from CharSequence (typically, `String`s).
config.setAutoEscape( );
model = < , >();
model.put("unsafeContents", "I am an <html> hacker.");
html {
body {
div(unsafeContents)
}
}
Then you wouldn’t want the HTML from unsafeContents to be rendered as is, because of potential security issues:
I am an hacker.
config.setAutoEscape( );
I am an <html> hacker.
Note that using automatic escaping doesn’t prevent you from including unescaped contents from the model. To do this, your
template should then explicitly mention that a model variable should not be escaped by pre xing it with unescaped. , like in this
example:
html {
body {
div(unescaped.unsafeContents)
}
}
Common gotchas
Strings containing markup
Say that you want to generate a <p> tag which contains a string containing markup:
p {
"This is a "
a(href:'target.html', "link")
" to another page"
}
and generates:
http://docs.groovy-lang.org/latest/html/documentation/ 375/502
1/6/2019 Can’t this be written shorter? A naive alternative would be:Groovy Language Documentation
p {
"This is a ${a(href:'target.html', "link")} to another page"
}
The reason is that the markup template engine is a streaming engine. In the original version, the rst yield call generates a
string which is streamed to the output, then the a link is generated and streamed, and then the last yield call is streamed,
leading in an execution in order. But with the string version above, the order of execution is di erent:
so evaluating the string leads to an execution of the a(href:…) call before yield is itself called. This is not what you want to do.
Instead, you want to generate a string which contains markup, which is then passed to the yield call. This can be done this way:
Note the stringOf call, which basically tells the markup template engine that the underlying markup needs to be rendered
separately and exported as a string. Note that for simple expressions, stringOf can be replaced by an alternate tag notation that
starts with a dollar sign:
It is worth noting that using stringOf or the special $tag notation triggers the creation of a distinct string writer
which is then used to render the markup. It is slower than using the version with calls to yield which perform
direct streaming of the markup instead.
Internationalization
The template engine has native support for internationalization. For that, when you create the TemplateConfiguration , you can
provide a Locale which is the default locale to be used for templates. Each template may have di erent versions, one for each
locale. The name of the template makes the di erence:
if the template name or include name explicitly sets a locale, the speci c version is included, or the default version if not found
if the template name doesn’t include a locale, the version for the TemplateConfiguration locale is used, or the default
version if not found
For example, imagine the default locale is set to Locale.ENGLISH and that the main template includes:
include : 'locale_include_fr_FR.tpl'
Texte en français
http://docs.groovy-lang.org/latest/html/documentation/ 376/502
1/6/2019 Using an include without specifying a locale will make the Groovy
template engine look
Language for a template with the con gured locale, and if
Documentation
not, fallback to the default, like here:
include : 'locale_include.tpl'
Default text
However, changing the default locale of the template engine to Locale.FRANCE will change the output, because the template
engine will now look for a le with the fr_FR locale:
Don’t fallback to the default template because a locale speci c template was found
Texte en français
This strategy lets you translate your templates one by one, by relying on default templates, for which no locale is set in the le
name.
The template engine provides this ability by setting an alternative baseTemplateClass in the TemplateConfiguration :
config.setBaseTemplateClass( . );
The custom base class has to extend BaseClass like in this example:
{
< > modules
(
templateEngine,
model,
< , > modelTypes,
configuration) {
(templateEngine, model, modelTypes, configuration)
}
hasModule( name) {
modules?.any { it.name == name }
}
}
This example shows a class which provides an additional method named hasModule , which can then be used directly in the
template:
(hasModule('foo')) {
p 'Found module [foo]'
} {
p 'Module [foo] not found'
}
http://docs.groovy-lang.org/latest/html/documentation/ 377/502
1/6/2019 Type checked templates Groovy Language Documentation
The MarkupTemplateEngine provides such a facility. Templates can be optionally type checked. For that, the developer must
provide additional information at template creation time, which is the types of the variables found in the model. Imagine a model
exposing a list of pages, where a page is de ned as:
Page.groovy
id
title
body
}
p = ();
p.setTitle("Sample page");
p.setBody("Page body");
< > pages = <>();
pages.add(p);
model = < , >();
model.put("pages", pages);
p(page.text) 3
Without type checking, the compilation of the template succeeds, because the template engine doesn’t know about the model
until a page is actually rendered. This means that the problem would only surface at runtime, once the page is rendered:
Runtime error
In some situations, this can be complicated to sort out or even notice. By declaring the type of the pages to the template engine,
we’re now capable of failing at compile time:
modelTypes.put("pages", "List<Page>"); 2
= engine.createTypeCheckedModelTemplate("main.tpl", modelTypes) 3
This time, when the template is compiled at the last line, an error occurs:
This means that you don’t need to wait for the page to be rendered to see an error. The use of
createTypeCheckedModelTemplate is mandatory.
modelTypes = { 1
This feature will automatically compile your .groovy source les, turn them into bytecode, load the Class and cache it until you
change the source le.
Here’s a simple example to show you the kind of things you can do from a Groovlet.
Notice the use of implicit variables to access the session, output and request. Also notice that this is more like a script as it does
not have a class wrapper.
http://docs.groovy-lang.org/latest/html/documentation/ 379/502
1/6/2019 Groovy Language Documentation
(!session) {
session = request.getSession( )
}
(!session.counter) {
session.counter = 1
}
println """
<html>
<head>
<title>Groovy Servlet</title>
</head>
<body>
<p>
Hello, ${request.remoteHost}: ${session.counter}! ${new Date()}
</p>
</body>
</html>
"""
session.counter = session.counter + 1
(!session) {
session = request.getSession( )
}
(!session.counter) {
session.counter = 1
}
request ServletRequest -
response ServletResponse -
context ServletContext -
application ServletContext -
http://docs.groovy-lang.org/latest/html/documentation/ 380/502
1/6/2019 Groovy Language Documentation
variable name bound to note
1. The session variable is only set, if there was already a session object. See the if (session == null) checks in the examples
above.
2. These variables cannot be re-assigned inside a Groovlet . They are bound on rst access, allowing to e.g. calling methods on
the response object before using out .
Groovy
groovy.servlet.GroovyServlet
Groovy
*.groovy
Now put the .groovy les in, say, the root directory (i.e. where you would put your html les). The GroovyServlet takes care of
compiling the .groovy les.
So for example using tomcat you could edit tomcat/conf/server.xml like this:
path="/groovy" docBase="c:/groovy-servlet"
All the examples written in this section are using Groovy, but the same integration mechanisms can be used from
Java.
Eval
The groovy.util.Eval class is the simplest way to execute Groovy dynamically at runtime. This can be done by calling the me
method:
http://docs.groovy-lang.org/latest/html/documentation/ 381/502
1/6/2019 Groovy Language Documentation
groovy.util.
.me('33*3') == 99
.me('"foo".toUpperCase()') == 'FOO'
Eval supports multiple variants that accept parameters for simple evaluation:
.x(4, '2*x') == 8 1
.me('k', 4, '2*k') == 8 2
.xy(4, 5, 'x*y') == 20 3
.xyz(4, 5, 6, 'x*y+z') == 26 4
The Eval class makes it very easy to evaluate simple scripts, but doesn’t scale: there is no caching of the script, and it isn’t meant
to evaluate more than one liners.
GroovyShell
Multiple sources
The groovy.lang.GroovyShell class is the preferred way to evaluate scripts with the ability to cache the resulting script
instance. Although the Eval class returns the result of the execution of the compiled script, the GroovyShell class o ers more
options.
shell = () 1
result == result2
script = shell.parse '3*5' 4
script groovy.lang.
script.run() == 15 5
sharedData = () 1
shell = (sharedData) 2
now = ()
sharedData.setProperty('text', 'I am shared data!') 3
sharedData.setProperty('date', now) 4
Note that it is also possible to write from the script into the binding:
sharedData = () 1
shell = (sharedData) 2
shell.evaluate('foo=123') 3
sharedData.getProperty('foo') == 123 4
It is important to understand that you need to use an undeclared variable if you want to write into the binding. Using def or an
explicit type like in the example below would fail because you would then create a local variable:
sharedData = ()
shell = (sharedData)
shell.evaluate('int foo=123')
{
sharedData.getProperty('foo')
} ( e) {
println "foo is defined as a local variable"
}
You must be very careful when using shared data in a multithreaded environment. The Binding instance that
you pass to GroovyShell is not thread safe, and shared by all scripts.
It is possible to work around the shared instance of Binding by leveraging the Script instance which is returned by parse :
shell = ()
b1 = (x:3) 1
b2 = (x:4) 2
However, you must be aware that you are still sharing the same instance of a script. So this technique cannot be used if you have
two threads working on the same script. In that case, you must make sure of creating two distinct script instances:
http://docs.groovy-lang.org/latest/html/documentation/ 383/502
1/6/2019 Groovy Language Documentation
shell = ()
b1 = (x:3)
b2 = (x:4)
script1 = shell.parse('x = 2*x') 1
script1 != script2
script1.binding = b1 3
script2.binding = b2 4
t1 = .start { script1.run() } 5
t2 = .start { script2.run() } 6
[t1,t2]*.join() 7
b1.getProperty('x') == 6
b2.getProperty('x') == 8
b1 != b2
In case you need thread safety like here, it is more advisable to use the GroovyClassLoader directly instead.
{
name
greet() {
"Hello, $name!"
}
}
The custom class de nes a property called name and a new method called greet . This class can be used as the script base class
by using a custom con guration:
org.codehaus.groovy.control.
config = () 1
config.scriptBaseClass = 'MyScript' 2
script = shell.parse('greet()') 4
script
script.setName('Michel')
script.run() == 'Hello, Michel!'
You are not limited to the sole scriptBaseClass con guration. You can use any of the compiler con guration
tweaks, including the compilation customizers.
http://docs.groovy-lang.org/latest/html/documentation/ 384/502
1/6/2019 GroovyClassLoader Groovy Language Documentation
In the previous section, we have shown that GroovyShell was an easy tool to execute scripts, but it makes it complicated to
compile anything but scripts. Internally, it makes use of the groovy.lang.GroovyClassLoader , which is at the heart of the
compilation and loading of classes at runtime.
By leveraging the GroovyClassLoader instead of GroovyShell , you will be able to load classes, instead of instances of scripts:
groovy.lang.
gcl = () 1
clazz.name == 'Foo' 3
o = clazz.newInstance() 4
o.doIt() 5
A GroovyClassLoader keeps a reference of all the classes it created, so it is easy to create a memory leak. In
particular, if you execute the same script twice, if it is a String, then you obtain two distinct classes!
groovy.lang.
gcl = ()
clazz1 = gcl.parseClass('class Foo { }') 1
clazz1.name == 'Foo' 3
clazz2.name == 'Foo'
clazz1 != clazz2 4
The reason is that a GroovyClassLoader doesn’t keep track of the source text. If you want to have the same instance, then the
source must be a le, like in this example:
gcl = ()
clazz1 = gcl.parseClass(file) 1
clazz1.name == 'Foo' 3
clazz2.name == 'Foo'
clazz1 == clazz2 4
Using a File as input, the GroovyClassLoader is capable of caching the generated class le, which avoids creating multiple
classes at runtime for the same source.
GroovyScriptEngine
http://docs.groovy-lang.org/latest/html/documentation/ 385/502
1/6/2019 The groovy.util.GroovyScriptEngine class provides aGroovy
exibleLanguage
foundation for applications which rely on script reloading and
Documentation
script dependencies. While GroovyShell focuses on standalone Script`s and `GroovyClassLoader handles dynamic
compilation and loading of any Groovy class, the GroovyScriptEngine will add a layer on top of GroovyClassLoader to handle
both script dependencies and reloading.
To illustrate this, we will create a script engine and execute code in an in nite loop. First of all, you need to create a directory with
the following script inside:
ReloadingTest.groovy
{
sayHello() {
greet = "Hello, world!"
greet
}
}
()
binding = ()
engine = ([tmpDir.toURI().toURL()] URL[]) 1
( ) {
greeter = engine.run('ReloadingTest.groovy', binding) 2
println greeter.sayHello() 3
.sleep(1000)
}
1 create a script engine which will look for sources into our source directory
2 execute the script, which will return an instance of Greeter
3 print the greeting message
Hello, world!
Hello, world!
...
Without interrupting the script execution, now replace the contents of the ReloadingTest le with:
ReloadingTest.groovy
{
sayHello() {
greet = "Hello, Groovy!"
greet
}
}
()
Hello, world!
...
Hello, Groovy!
Hello, Groovy!
...
But it is also possible to have a dependency on another script. To illustrate this, create the following le into the same directory,
without interrupting the executing script:
http://docs.groovy-lang.org/latest/html/documentation/ 386/502
1/6/2019 Depencency.groovy Groovy Language Documentation
{
message = 'Hello, dependency 1'
}
ReloadingTest.groovy
{
sayHello() {
greet = ().message
greet
}
}
()
Hello, Groovy!
...
Hello, dependency 1!
Hello, dependency 1!
...
And as a last test, you can update the Dependency.groovy le without touching the ReloadingTest le:
Depencency.groovy
{
message = 'Hello, dependency 2'
}
Hello, dependency 1!
...
Hello, dependency 2!
Hello, dependency 2!
CompilationUnit
Ultimately, it is possible to perform more operations during compilation by relying directly on the
org.codehaus.groovy.control.CompilationUnit class. This class is responsible for determining the various steps of
compilation and would let you introduce new steps or even stop compilation at various phases. This is for example how stub
generation is done, for the joint compiler.
However, overriding CompilationUnit is not recommended and should only be done if no other standard solution works.
The BSF engine for Groovy is implemented by the org.codehaus.groovy.bsf.GroovyEngine class. However, that fact is
normally hidden away by the BSF APIs. You just treat Groovy like any of the other scripting languages via the BSF API.
http://docs.groovy-lang.org/latest/html/documentation/ 387/502
1/6/2019 Groovy Language Documentation
Since Groovy has its own native support for integration with Java, you only need to worry about BSF if you also
want to also be able to call other languages, e.g. JRuby (https://www.jruby.org/) or if you want to remain very
loosely coupled from your scripting language.
Getting started
Provided you have Groovy and BSF jars in your classpath, you can use the following Java code to run a sample Groovy script:
Passing in variables
BSF lets you pass beans between Java and your scripting language. You can register/unregister beans which makes them known to
BSF. You can then use BSF methods to lookup beans as required. Alternatively, you can declare/undeclare beans. This will register
them but also make them available for use directly in your scripting language. This second approach is the normal approach used
with Groovy. Here is an example:
manager = ();
manager.declareBean("xyz", 4, . );
answer = manager.eval("groovy", "test.groovy", 0, 0, "xyz + 1");
assertEquals(5, answer);
manager = ();
< > ignoreParamNames = ;
< > args = < >();
args.add(2);
args.add(5);
args.add(1);
actual = ( ) manager.apply("groovy", "applyTest", 0, 0,
"def summer = { a, b, c -> a * 100 + b * 10 + c }", ignoreParamNames, args);
assertEquals(251, actual.intValue());
manager = ();
bsfEngine = manager.loadScriptingEngine("groovy");
manager.declareBean("myvar", "hello", . );
myvar = manager.lookupBean("myvar");
result = ( ) bsfEngine.call(myvar, "reverse", [0]);
assertEquals("olleh", result);
JSR-223 is a standard API for calling scripting frameworks in Java. It is available since Java 6 and aims at providing a
common framework for calling multiple languages from Java. Groovy provides its own richer integration
mechanisms, and if you don’t plan to use multiple languages in the same application, it is recommended that you
use the Groovy integration mechanisms instead of the limited JSR-223 API.
Here is how you need to initialize the JSR-223 engine to talk to Groovy from Java:
http://docs.groovy-lang.org/latest/html/documentation/ 388/502
1/6/2019 Groovy Language Documentation
javax.script. ;
javax.script. ;
javax.script. ;
...
factory = ();
engine = factory.getEngineByName("groovy");
sum = ( ) engine.eval("(1..10).sum()");
assertEquals( (55), sum);
engine.put("first", "HELLO");
engine.put("second", "world");
result = ( ) engine.eval("first.toLowerCase() + ' ' + second.toUpperCase()");
assertEquals("hello WORLD", result);
javax.script. ;
...
factory = ();
engine = factory.getEngineByName("groovy");
fact = "def factorial(n) { n == 1 ? 1 : n * factorial(n - 1) }";
engine.eval(fact);
inv = ( ) engine;
[] params = {5};
result = inv.invokeFunction("factorial", params);
assertEquals( (120), result);
The engine keeps per default hard references to the script functions. To change this you should set a engine level scoped attribute
to the script context of the name #jsr223.groovy.engine.keep.globals with a String being phantom to use phantom
references, weak to use weak references or soft to use soft references - casing is ignored. Any other string will cause the use of
hard references.
If your command chain contains an odd number of elements, the chain will be composed of method / arguments, and will nish
by a nal property access:
This command chain approach opens up interesting possibilities in terms of the much wider range of DSLs which can now be
written in Groovy.
The above examples illustrate using a command chain based DSL but not how to create one. There are various strategies that you
can use, but to illustrate creating such a DSL, we will show a couple of examples - rst using maps and Closures:
show = { println it }
square_root = { .sqrt(it) }
please(action) {
[the: { what ->
[of: { n -> action(what(n)) }]
}]
}
As a second example, consider how you might write a DSL for simplifying one of your existing APIs. Maybe you need to put this
code in front of customers, business analysts or testers who might be not hard-core Java developers. We’ll use the Splitter
from the Google Guava libraries (https://github.com/google/guava) project as it already has a nice Fluent API. Here is how we
might use it out of the box:
@Grab('com.google.guava:guava:r09')
com.google.common. .*
result = .on(',').trimResults( . ('_' )).split("_a ,_b_
,c__").iterator().toList()
It reads fairly well for a Java developer but if that is not your target audience or you have many such statements to write, it could
be considered a little verbose. Again, there are many options for writing a DSL. We’ll keep it simple with Maps and Closures. We’ll
rst write a helper method:
@Grab('com.google.guava:guava:r09')
com.google.common. .*
split( ) {
[on: { sep ->
[trimming: { trimChar ->
.on(sep).trimResults( . (trimChar
)).split( ).iterator().toList()
}]
}]
}
This allows you to provide your own Java or Groovy objects which can take advantage of operator overloading. The following table
describes the operators supported in Groovy and the methods they map to.
Operator Method
a + b a.plus(b)
a - b a.minus(b)
a * b a.multiply(b)
a ** b a.power(b)
a / b a.div(b)
a % b a.mod(b)
a | b a.or(b)
a & b a.and(b)
a ^ b a.xor(b)
a[b] a.getAt(b)
a[b] = c a.putAt(b, c)
a << b a.leftShift(b)
a >> b a.rightShift(b)
a >>> b a.rightShiftUnsigned(b)
if(a) a.asBoolean()
~a a.bitwiseNegate()
-a a.negative()
+a a.positive()
a as b a.asType(b)
a == b a.equals(b)
a != b ! a.equals(b)
a <=> b a.compareTo(b)
http://docs.groovy-lang.org/latest/html/documentation/ 391/502
1/6/2019 Groovy Language Documentation
Operator Method
binding = () 1
shell = (binding) 2
binding.setVariable('x',1) 3
binding.setVariable('y',3)
shell.evaluate 'z=2*x+y' 4
binding.getVariable('z') == 5 5
1 a binding is used to share data between the script and the calling class
2 a GroovyShell can be used with this binding
3 input variables are set from the calling class inside the binding
4 then the script is evaluated
5 and the z variable has been "exported" into the binding
This is a very practical way to share data between the caller and the script, however it may be insu cient or not practical in some
cases. For that purpose, Groovy allows you to set your own base script class. A base script class has to extend groovy.lang.Script
(http://docs.groovy-lang.org/2.5.5/html/gapi/index.html?groovy/lang/Script.html) and be a single abstract method type:
{
name
greet() { println "Hello, $name!" }
}
Then the custom script base class can be declared in the compiler con guration, for example:
config = () 1
config.scriptBaseClass = 'MyBaseClass' 2
shell.evaluate """
setName 'Judith' 4
greet()
"""
http://docs.groovy-lang.org/latest/html/documentation/ 392/502
1/6/2019 Groovy Language Documentation
groovy.transform.
@BaseScript baseScript
setName 'Judith'
greet()
where @BaseScript should annotate a variable which type is the class of the base script. Alternatively, you can set the base script
class as a member of the @BaseScript annotation itself:
@BaseScript( )
groovy.transform.
setName 'Judith'
greet()
{
count
scriptBody() 1
run() {
count++ 2
scriptBody() 3
count 4
}
}
1 the base script class should de ne one (and only one) abstract method
2 the run method can be overridden and perform a task before executing the script body
3 run calls the abstract scriptBody method which will delegate to the user script
4 then it can return something else than the value from the script
Then you will see that the script is executed, but the result of the evaluation is 1 as returned by the run method of the base
class. It is even clearer if you use parse instead of evaluate , because it would allow you to execute the run method several
times on the same script instance:
http://docs.groovy-lang.org/latest/html/documentation/ 393/502
1/6/2019 Groovy Language Documentation
( ) {
println 1.minute. .now 1
println 10.hours.ago
someDate = () 2
Categories are lexically bound, making them a great t for internal DSLs.
3.15.5. @DelegatesTo
providing type information for the static type checker and compiler
The Groovy language is a platform of choice for building DSLs. Using closures, it’s quite easy to create custom control structures,
as well as it is simple to create builders. Imagine that you have the following code:
email {
'[email protected]'
to '[email protected]'
subject 'The pope has resigned!'
body {
p 'Really, the pope has resigned!'
}
}
One way of implementing this is using the builder strategy, which implies a method, named email which accepts a closure as an
argument. The method may delegate subsequent calls to an object that implements the from , to , subject and body methods.
Again, body is a method which accepts a closure as an argument and that uses the builder strategy.
email( cl) {
email = ()
code = cl.rehydrate(email, , )
code.resolveStrategy = .DELEGATE_ONLY
code()
}
the EmailSpec class implements the from , to , … methods. By calling rehydrate , we’re creating a copy of the closure for which
we set the delegate , owner and thisObject values. Setting the owner and the this object is not very important here since
we will use the DELEGATE_ONLY strategy which says that the method calls will be resolved only against the delegate of the closure.
{
( ) { println "From: $from"}
to( ... to) { println "To: $to"}
subject( subject) { println "Subject: $subject"}
body( body) {
bodySpec = ()
code = body.rehydrate(bodySpec, , )
code.resolveStrategy = .DELEGATE_ONLY
code()
}
}
http://docs.groovy-lang.org/latest/html/documentation/ 394/502
1/6/2019 The EmailSpec class has itself a body method acceptingGroovy
a closure that is cloned
Language and executed. This is what we call the builder
Documentation
pattern in Groovy.
One of the problems with the code that we’ve shown is that the user of the email method doesn’t have any information about
the methods that he’s allowed to call inside the closure. The only possible information is from the method documentation. There
are two issues with this: rst of all, documentation is not always written, and if it is, it’s not always available (javadoc not
downloaded, for example). Second, it doesn’t help IDEs. What would be really interesting, here, is for IDEs to help the developer by
suggesting, once they are in the closure body, methods that exist on the email class.
Moreover, if the user calls a method in the closure which is not de ned by the EmailSpec class, the IDE should at least issue a
warning (because it’s very likely that it will break at runtime).
One more problem with the code above is that it is not compatible with static type checking. Type checking would let the user
know if a method call is authorized at compile time instead of runtime, but if you try to perform type checking on this code:
email {
'[email protected]'
to '[email protected]'
subject 'The pope has resigned!'
body {
p 'Really, the pope has resigned!'
}
}
Then the type checker will know that there’s an email method accepting a Closure , but it will complain for every method
call inside the closure, because from , for example, is not a method which is de ned in the class. Indeed, it’s de ned in
the EmailSpec class and it has absolutely no hint to help it knowing that the closure delegate will, at runtime, be of
type EmailSpec :
@groovy.transform.
sendEmail() {
email {
'[email protected]'
to '[email protected]'
subject 'The pope has resigned!'
body {
p 'Really, the pope has resigned!'
}
}
}
[Static type checking] - Cannot find matching method MyScript#from(java.lang.String). Please check
if the declared type is right and if the method exists.
@ line 31, column 21.
from '[email protected]'
@DelegatesTo
For those reasons, Groovy 2.1 introduced a new annotation named @DelegatesTo . The goal of this annotation is to solve both
the documentation issue, that will let your IDE know about the expected methods in the closure body, and it will also solve the
type checking issue, by giving hints to the compiler about what are the potential receivers of method calls in the closure body.
email(@DelegatesTo( ) cl) {
email = ()
code = cl.rehydrate(email, , )
code.resolveStrategy = .DELEGATE_ONLY
code()
}
http://docs.groovy-lang.org/latest/html/documentation/ 395/502
1/6/2019 What we’ve done here is telling the compiler (or the IDE) that when
Groovy the method
Language will be called with a closure, the delegate of this
Documentation
closure will be set to an object of type email . But there is still a problem: the default delegation strategy is not the one which is
used in our method. So we will give more information and tell the compiler (or the IDE) that the delegation strategy is also
changed:
Now, both the IDE and the type checker (if you are using @TypeChecked ) will be aware of the delegate and the delegation
strategy. This is very nice because it will both allow the IDE to provide smart completion, but it will also remove errors at compile
time that exist only because the behaviour of the program is normally only known at runtime!
@TypeChecked
doEmail() {
email {
'[email protected]'
to '[email protected]'
subject 'The pope has resigned!'
body {
p 'Really, the pope has resigned!'
}
}
}
DelegatesTo modes
@DelegatesTo supports multiple modes that we will describe with examples in this section.
Simple delegation
In this mode, the only mandatory parameter is the value which says to which class we delegate calls. Nothing more. We’re telling
the compiler that the type of the delegate will always be of the type documented by @DelegatesTo (note that it can be a
subclass, but if it is, the methods de ned by the subclass will not be visible to the type checker).
body(@DelegatesTo( ) cl) {
// ...
}
Delegation strategy
In this mode, you must specify both the delegate class and a delegation strategy. This must be used if the closure will not be called
with the default delegation strategy, which is Closure.OWNER_FIRST .
Delegate to parameter
In this variant, we will tell the compiler that we are delegating to another parameter of the method. Take the following code:
( target, code) {
clone = code.rehydrate(target, , )
clone()
}
Here, the delegate which will be used is not created inside the exec method. In fact, we take an argument of the method and
delegate to it. Usage may look like this:
http://docs.groovy-lang.org/latest/html/documentation/ 396/502
1/6/2019 Groovy Language Documentation
email = ()
(email) {
'...'
to '...'
send()
}
Each of the method calls are delegated to the email parameter. This is a widely used pattern which is also supported
by @DelegatesTo using a companion annotation:
A closure is annotated with @DelegatesTo , but this time, without specifying any class. Instead, we’re annotating another
parameter with @DelegatesTo.Target . The type of the delegate is then determined at compile time. One could think that we are
using the parameter type, which in this case is Object but this is not true. Take this code:
{
sayHello() { println 'Hello' }
}
greeter = ()
(greeter) {
sayHello()
}
Remember that this works out of the box without having to annotate with @DelegatesTo . However, to make the IDE aware of
the delegate type, or the type checker aware of it, we need to add @DelegatesTo . And in this case, it will know that the Greeter
variable is of type Greeter , so it will not report errors on the sayHello method even if the exec method doesn’t explicitly de ne
the target as of type Greeter. This is a very powerful feature, because it prevents you from writing multiple versions of the
same exec method for di erent receiver types!
In this mode, the @DelegatesTo annotation also supports the strategy parameter that we’ve described upper.
Multiple closures
In the previous example, the exec method accepted only one closure, but you may have methods that take multiple closures:
Then nothing prevents you from annotating each closure with @DelegatesTo :
But more importantly, if you have multiple closures and multiple arguments, you can use several targets:
http://docs.groovy-lang.org/latest/html/documentation/ 397/502
1/6/2019 Groovy Language Documentation
fooBarBaz(
@DelegatesTo. ('foo') foo,
@DelegatesTo. ('bar') bar,
@DelegatesTo. ('baz') baz,
@DelegatesTo(target='foo') cl1,
@DelegatesTo(target='bar') cl2,
@DelegatesTo(target='baz') cl3) {
cl1.rehydrate(foo, , ).call()
cl2.rehydrate(bar, , ).call()
cl3.rehydrate(baz, , ).call()
}
a = ()
b = ()
c = ()
fooBarBaz(
a, b, c,
{ foo('Hello') },
{ bar(123) },
{ baz( ()) }
)
At this point, you may wonder why we don’t use the parameter names as references. The reason is that the
information (the parameter name) is not always available (it’s a debug-only information), so it’s a limitation of the
JVM.
Then this method can be called with any list like this:
@groovy.transform.
{
name
}
< > list = []
3.times { list << () }
configure(list) {
name = 'My Realm'
}
list.every { it.name == 'My Realm' }
To let the type checker and the IDE know that the configure method calls the closure on each element of the list, you need to
use @DelegatesTo di erently:
<T> configure(
@DelegatesTo. <T> elements,
@DelegatesTo(strategy= .DELEGATE_FIRST, genericTypeIndex=0) configuration) {
clone = configuration.rehydrate(e, , )
clone.resolveStrategy = .DELEGATE_FIRST
clone.call()
}
http://docs.groovy-lang.org/latest/html/documentation/ 398/502
1/6/2019 @DelegatesTo takes an optional genericTypeIndex argument that tells what
Groovy Language is the index of the generic type that will be used
Documentation
as the delegate type. This must be used in conjunction with @DelegatesTo.Target and the index starts at 0. In the example
above, that means that the delegate type is resolved against List<T> , and since the generic type at index 0 is T and inferred as
a Realm , the type checker infers that the delegate type will be of type Realm .
<T,U> { 1
T value 2
producer. = value
producer()
}
}
1 The mapper class takes two generic type arguments: the source type and the target type
2 The source object is stored in a nal eld
3 The map method asks to convert the source object to a target object
As you can see, the method signature from map does not give any information about what object will be manipulated by the
closure. Reading the method body, we know that it will be the value which is of type T , but T is not found in the method
signature, so we are facing a case where none of the available options for @DelegatesTo is suitable. For example, if we try to
statically compile this code:
In that case, you can use the type member of the @DelegatesTo annotation to reference T as a type token:
<T,U> {
T value
(T value) { .value = value }
U map(@DelegatesTo(type="T") <U> producer) { 1
producer. = value
producer()
}
}
1 The @DelegatesTo annotation references a generic type which is not found in the method signature
Note that you are not limited to generic type tokens. The type member can be used to represent complex types, such as
List<T> or Map<T,List<U>> . The reason why you should use that in last resort is that the type is only checked when the type
checker nds usage of @DelegatesTo , not when the annotated method itself is compiled. This means that type safety is only
ensured at the call site. Additionally, compilation will be slower (though probably unnoticeable for most cases).
Introduction
Whether you are using groovyc to compile classes or a GroovyShell , for example, to execute scripts, under the hood, a
compiler con guration is used. This con guration holds information like the source encoding or the classpath but it can also be
used to perform more operations like adding imports by default, applying AST transformations transparently or disabling global
http://docs.groovy-lang.org/latest/html/documentation/ 399/502
1/6/2019 AST transformations. Groovy Language Documentation
The goal of compilation customizers is to make those common tasks easy to implement. For that, the CompilerConfiguration
class is the entry point. The general schema will always be based on the following code:
org.codehaus.groovy.control.
// create a configuration
config = ()
// tweak the configuration
config.addCompilationCustomizers(...)
// run your script
shell = (config)
shell.evaluate(script)
You can implement your own compilation customizer but Groovy includes some of the most common operations.
Import customizer
Using this compilation customizer, your code will have imports added transparently. This is in particular useful for scripts
implementing a DSL where you want to avoid users from having to write imports. The import customizer will let you add all the
variants of imports the Groovy language allows, that is:
star imports
org.codehaus.groovy.control.customizers.
icz = ()
// "normal" import
icz.addImports('java.util.concurrent.atomic.AtomicInteger',
'java.util.concurrent.ConcurrentHashMap')
// "aliases" import
icz.addImport('CHM', 'java.util.concurrent.ConcurrentHashMap')
// "static" import
icz.addStaticImport('java.lang.Math', 'PI') // import static java.lang.Math.PI
// "aliased static" import
icz.addStaticImport('pi', 'java.lang.Math', 'PI') // import static java.lang.Math.PI as pi
// "star" import
icz.addStarImports 'java.util.concurrent' // import java.util.concurrent.*
// "static star" import
icz.addStaticStars 'java.lang.Math' // import static java.lang.Math.*
As an example, let’s say you want to be able to use @Log in a script. The problem is that @Log is normally applied on a class node
and a script, by de nition, doesn’t require one. But implementation wise, scripts are classes, it’s just that you cannot annotate this
implicit class node with @Log . Using the AST customizer, you have a workaround to do it:
http://docs.groovy-lang.org/latest/html/documentation/ 400/502
1/6/2019 Groovy Language Documentation
org.codehaus.groovy.control.customizers.
groovy.util.logging.
acz = ( )
config.addCompilationCustomizers(acz)
That’s all! Internally, the @Log AST transformation is applied to every class node in the compilation unit. This means that it will be
applied to the script, but also to classes de ned within the script.
If the AST transformation that you are using accepts parameters, you can use parameters in the constructor too:
As the AST transformation customizers works with objects instead of AST nodes, not all values can be converted to AST
transformation parameters. For example, primitive types are converted to ConstantExpression (that is LOGGER is converted
to new ConstantExpression('LOGGER') , but if your AST transformation takes a closure as an argument, then you have to give it
a ClosureExpression , like in the following example:
configuration = ()
expression = ().buildFromCode( .CONVERSION) { -> }.expression[0]
customizer = ( , value: expression, thrown:
)
configuration.addCompilationCustomizers(customizer)
shell = (configuration)
shouldFail( ) {
shell.evaluate("""
// equivalent to adding @ConditionalInterrupt(value={true}, thrown: SecurityException)
class MyClass {
void doIt() { }
}
new MyClass().doIt()
""")
}
allow/disallow imports
http://docs.groovy-lang.org/latest/html/documentation/ 401/502
1/6/2019 For all those features, the secure AST customizer works using either
Groovy a whitelist
Language (list of elements that are allowed) or a blacklist (list
Documentation
of elements that are disallowed). For each type of feature (imports, tokens, …) you have the choice to use either a whitelist or a
blacklist, but you can mix whitelists and blacklists for distinct features. In general, you will choose whitelists (disallow all, allow
selected).
org.codehaus.groovy.control.customizers.
org.codehaus.groovy.syntax. .* 1
scz = ()
scz. {
closuresAllowed = // user will not be able to write closures
methodDefinitionAllowed = // user will not be able to define methods
importsWhitelist = [] // empty whitelist means imports are disallowed
staticImportsWhitelist = [] // same for static imports
staticStarImportsWhitelist = ['java.lang.Math'] // only java.lang.Math is allowed
// the list of tokens the user can find
// constants are defined in org.codehaus.groovy.syntax.Types
tokensWhitelist = [ 1
PLUS,
MINUS,
MULTIPLY,
DIVIDE,
MOD,
POWER,
PLUS_PLUS,
MINUS_MINUS,
COMPARE_EQUAL,
COMPARE_NOT_EQUAL,
COMPARE_LESS_THAN,
COMPARE_LESS_THAN_EQUAL,
COMPARE_GREATER_THAN,
COMPARE_GREATER_THAN_EQUAL,
].asImmutable()
// limit the types of constants that a user can define to number types only
constantTypesClassesWhiteList = [ 2
,
,
,
,
,
.TYPE,
.TYPE,
.TYPE,
.TYPE
].asImmutable()
// method calls are only allowed if the receiver is of one of those types
// be careful, it's not a runtime type!
receiversClassesWhiteList = [ 2
,
,
,
,
,
].asImmutable()
}
If what the secure AST customizer provides out of the box isn’t enough for your needs, before creating your own compilation
customizer, you might be interested in the expression and statement checkers that the AST customizer supports. Basically, it
allows you to add custom checks on the AST tree, on expressions (expression checkers) or statements (statement checkers). For
http://docs.groovy-lang.org/latest/html/documentation/ 402/502
1/6/2019 this, you must implement org.codehaus.groovy.control.customizers.SecureASTCustomizer.StatementChecker
Groovy Language Documentation
or org.codehaus.groovy.control.customizers.SecureASTCustomizer.ExpressionChecker .
Those interfaces de ne a single method called isAuthorized , returning a boolean, and taking a Statement (or Expression ) as
a parameter. It allows you to perform complex logic over expressions or statements to tell if a user is allowed to do it or not.
For example, there’s no prede ned con guration ag in the customizer which will let you prevent people from using an attribute
expression. Using a custom checker, it is trivial:
scz = ()
checker = { expr ->
!(expr )
} .
scz.addExpressionCheckers(checker)
Then we can make sure that this works by evaluating a simple script:
(config).evaluate '''
class A {
int val
}
SourceUnit gives you access to multiple things but in particular the le being compiled (if compiling from a le, of course). It
gives you the potential to perform operation based on the le name, for example. Here is how you would create a source aware
customizer:
org.codehaus.groovy.control.customizers.
org.codehaus.groovy.control.customizers.
= ()
sac = ( )
http://docs.groovy-lang.org/latest/html/documentation/ 403/502
1/6/2019 Groovy Language Documentation
// the customizer will only be applied to classes contained in a file name ending with 'Bean'
sac.baseNameValidator = { baseName ->
baseName.endsWith 'Bean'
}
// class validation
// the customizer will only be applied to classes ending with 'Bean'
sac.classValidator = { cn -> cn.endsWith('Bean') }
Customizer builder
If you are using compilation customizers in Groovy code (like the examples above) then you can use an alternative syntax to
customize compilation. A builder ( org.codehaus.groovy.control.customizers.builder.CompilerCustomizationBuilder )
simpli es the creation of customizers using a hierarchical DSL.
org.codehaus.groovy.control.
org.codehaus.groovy.control.customizers.builder. .withConfig
1
conf = ()
withConfig(conf) {
// ... 2
}
The code sample above shows how to use the builder. A static method, withCon g, takes a closure corresponding to the builder
code, and automatically registers compilation customizers to the con guration. Every compilation customizer available in the
distribution can be con gured this way:
Import customizer
withConfig(configuration) {
imports { // imports customizer
normal 'my.package.MyClass' // a normal import
'AI', 'java.util.concurrent.atomic.AtomicInteger' // an aliased import
star 'java.util.concurrent' // star imports
staticMember 'java.lang.Math', 'PI' // static import
staticMember 'pi', 'java.lang.Math', 'PI' // aliased static import
}
}
withConfig(conf) {
ast( ) 1
}
withConfig(conf) {
ast( , value: 'LOGGER') 2
http://docs.groovy-lang.org/latest/html/documentation/ 404/502
1/6/2019 Groovy Language Documentation
withConfig(conf) {
secureAst {
closuresAllowed =
methodDefinitionAllowed =
}
}
withConfig(configuration){
source(extension: 'sgroovy') {
ast( ) 1
}
}
withConfig(configuration){
source(extensions: ['sgroovy','sg']) {
ast( ) 2
}
}
withConfig(configuration) {
source(extensionValidator: { it.name ['sgroovy','sg']}) {
ast( ) 2
}
}
withConfig(configuration) {
source(basename: 'foo') {
ast( ) 3
}
}
withConfig(configuration) {
source(basenames: ['foo', 'bar']) {
ast( ) 4
}
}
withConfig(configuration) {
source(basenameValidator: { it ['foo', 'bar'] }) {
ast( ) 4
}
}
withConfig(configuration) {
source(unitValidator: { unit -> !unit.AST.classes.any { it.name == 'Baz' } }) {
ast( ) 5
}
}
Inlining a customizer
Inlined customizer allows you to write a compilation customizer directly, without having to create a class for it.
http://docs.groovy-lang.org/latest/html/documentation/ 405/502
1/6/2019 Groovy Language Documentation
withConfig(configuration) {
(phase:'CONVERSION') { source, context, classNode -> 1
}
}
Multiple customizers
Of course, the builder allows you to de ne multiple customizers at once:
withConfig(configuration) {
ast( )
ast( )
}
Con g script ag
So far, we have described how you can customize compilation using a CompilationConfiguration class, but this is only possible
if you embed Groovy and that you create your own instances of CompilerConfiguration (then use it to create a
GroovyShell , GroovyScriptEngine , …).
If you want it to be applied on the classes you compile with the normal Groovy compiler (that is to say with groovyc , ant
or gradle , for example), it is possible to use a compilation ag named configscript that takes a Groovy con guration script as
argument.
This script gives you access to the CompilerConfiguration instance before the les are compiled (exposed into the
con guration script as a variable named configuration ), so that you can tweak it.
It also transparently integrates the compiler con guration builder above. As an example, let’s see how you would activate static
compilation by default on all classes.
withConfig(configuration) { 1
ast(groovy.transform. )
}
That is actually all you need. You don’t have to import the builder, it’s automatically exposed in the script. Then, compile your les
using the following command line:
We strongly recommend you to separate con guration les from classes, hence why we suggest using the src/main and
src/conf directories above.
AST transformations
If:
you want to leverage the same syntax as Groovy but with di erent semantics
3.15.8. Builders
(TBD)
Creating a builder
(TBD)
BuilderSupport
(TBD)
FactoryBuilderSupport
(TBD)
Existing builders
(TBD)
MarkupBuilder
See Creating Xml - MarkupBuilder.
StreamingMarkupBuilder
See Creating Xml - StreamingMarkupBuilder.
SaxBuilder
A builder for generating Simple API for XML (SAX) (https://en.wikipedia.org/wiki/Simple_API_for_XML) events.
org.xml.sax.helpers. {
log = ''
You can use SaxBuilder to generate SAX events for the handler like this:
handler = ()
builder = groovy.xml. (handler)
builder.root() {
helloWorld()
}
http://docs.groovy-lang.org/latest/html/documentation/ 407/502
1/6/2019 And then check that everything worked as expected: Groovy Language Documentation
handler.log == 'Start Element: root, Start Element: helloWorld, End Element: helloWorld, End
Element: root, '
StaxBuilder
A Groovy builder that works with Streaming API for XML (StAX) (http://en.wikipedia.org/wiki/StAX) processors.
Here is a simple example using the StAX implementation of Java to generate XML:
builder.root(attribute:1) {
elem1('hello')
elem2('world')
}
@Grab('org.codehaus.jettison:jettison:1.3.3')
@GrabExclude('stax:stax-api') // part of Java 6 and later
org.codehaus.jettison.mapped.*
writer = ()
mappedWriter = ( (), writer)
builder = groovy.xml. (mappedWriter)
builder.root(attribute:1) {
elem1('hello')
elem2('world')
}
writer.toString() == '{"root":{"@attribute":"1","elem1":"hello","elem2":"world"}}'
DOMBuilder
A builder for parsing HTML, XHTML and XML into a W3C DOM (https://en.wikipedia.org/wiki/Document_Object_Model) tree.
recordsXML = '''
<records>
<car name='HSV ' make=' ' year='2006'>
<country>Australia</country>
<record type='speed'>Production Pickup Truck with speed of 271kph</record>
</car>
<car name='P50' make=' ' year='1962'>
<country>Isle of Man</country>
<record type='size'>Smallest Street-Legal Car at 99cm wide and 59 kg in weight</record>
</car>
<car name=' ' make=' ' year='1931'>
<country>France</country>
<record type='price'>Most Valuable Car at $15 million</record>
</car>
</records>'''
http://docs.groovy-lang.org/latest/html/documentation/ 408/502
1/6/2019 Groovy Language Documentation
reader = (recordsXML)
doc = groovy.xml. .parse(reader)
records = doc.documentElement
(groovy.xml.dom. ) {
records.car.size() == 3
}
NodeBuilder
NodeBuilder is used for creating nested trees of Node (http://docs.groovy-lang.org/2.5.5/html/gapi/index.html?
groovy/util/Node.html) objects for handling arbitrary data. To create a simple user list you use a NodeBuilder like this:
nodeBuilder = ()
userlist = nodeBuilder.userlist {
user(id: '1', firstname: 'John', lastname: 'Smith') {
address(type: 'home', street: '1 Main St.', city: 'Springfield', state: 'MA', zip:
'12345')
address(type: 'work', street: '2 South St.', city: 'Boston', state: 'MA', zip: '98765')
}
user(id: '2', firstname: 'Alice', lastname: 'Doe')
}
Now you can process the data further, e.g. by using GPath expressions:
JsonBuilder
Groovy’s JsonBuilder makes it easy to create Json. For example to create this Json string:
carRecords = '''
{
"records": {
"car": {
"name": "HSV Maloo",
"make": "Holden",
"year": 2006,
"country": "Australia",
"record": {
"type": "speed",
"description": "production pickup truck with speed of 271kph"
}
}
}
}
'''
http://docs.groovy-lang.org/latest/html/documentation/ 409/502
1/6/2019 Groovy Language Documentation
builder = ()
builder.records {
car {
name 'HSV Maloo'
make 'Holden'
year 2006
country 'Australia'
record {
type 'speed'
description 'production pickup truck with speed of 271kph'
}
}
}
json = .prettyPrint(builder.toString())
We use JsonUnit (https://github.com/lukas-krecan/JsonUnit) to check that the builder produced the expected result:
.assertJsonEquals(json, carRecords)
If you need to customize the generated output you can pass a JsonGenerator instance when creating a JsonBuilder :
groovy.json.*
generator = . ()
.excludeNulls()
.excludeFieldsByName('make', 'country', 'record')
.excludeFieldsByType( )
.addConverter(URL) { url -> "http://groovy-lang.org" }
.build()
builder = (generator)
builder.records {
car {
name 'HSV Maloo'
make 'Holden'
year 2006
country 'Australia'
homepage URL('http://example.org')
record {
type 'speed'
description 'production pickup truck with speed of 271kph'
}
}
}
StreamingJsonBuilder
Unlike JsonBuilder which creates a data structure in memory, which is handy in those situations where you want to alter the
structure programmatically before output, StreamingJsonBuilder directly streams to a writer without any intermediate
memory data structure. If you do not need to modify the structure and want a more memory-e cient approach, use
StreamingJsonBuilder .
The usage of StreamingJsonBuilder is similar to JsonBuilder . In order to create this Json string:
http://docs.groovy-lang.org/latest/html/documentation/ 410/502
1/6/2019 Groovy Language Documentation
carRecords = '''
{
"records": {
"car": {
"name": "HSV Maloo",
"make": "Holden",
"year": 2006,
"country": "Australia",
"record": {
"type": "speed",
"description": "production pickup truck with speed of 271kph"
}
}
}
}
'''
writer = ()
builder = (writer)
builder.records {
car {
name 'HSV Maloo'
make 'Holden'
year 2006
country 'Australia'
record {
type 'speed'
description 'production pickup truck with speed of 271kph'
}
}
}
json = .prettyPrint(writer.toString())
.assertJsonEquals(json, carRecords)
If you need to customize the generated output you can pass a JsonGenerator instance when creating a
StreamingJsonBuilder :
http://docs.groovy-lang.org/latest/html/documentation/ 411/502
1/6/2019 Groovy Language Documentation
generator = . ()
.excludeNulls()
.excludeFieldsByName('make', 'country', 'record')
.excludeFieldsByType( )
.addConverter(URL) { url -> "http://groovy-lang.org" }
.build()
writer = ()
builder = (writer, generator)
builder.records {
car {
name 'HSV Maloo'
make 'Holden'
year 2006
country 'Australia'
homepage URL('http://example.org')
record {
type 'speed'
description 'production pickup truck with speed of 271kph'
}
}
}
SwingBuilder
SwingBuilder allows you to create full- edged Swing GUIs in a declarative and concise fashion. It accomplishes this by
employing a common idiom in Groovy, builders. Builders handle the busywork of creating complex objects for you, such as
instantiating children, calling Swing methods, and attaching these children to their parents. As a consequence, your code is much
more readable and maintainable, while still allowing you access to the full range of Swing components.
groovy.swing.
java.awt. BL
count = 0
().edt {
frame(title: 'Frame', size: [300, 300], show: ) {
borderLayout()
textlabel = label(text: 'Click the button!', constraints: BL.NORTH)
button(text:'Click Me',
actionPerformed: {count++; textlabel.text = "Clicked ${count} time(s)."; println
"clicked"}, constraints:BL.SOUTH)
}
}
This hierarchy of components would normally be created through a series of repetitive instantiations, setters, and nally attaching
this child to its respective parent. Using SwingBuilder , however, allows you to de ne this hierarchy in its native form, which
makes the interface design understandable simply by reading the code.
The exibility shown here is made possible by leveraging the many programming features built-in to Groovy, such as closures,
implicit constructor calling, import aliasing, and string interpolation. Of course, these do not have to be fully understood in order
to use SwingBuilder ; as you can see from the code above, their uses are intuitive.
Here is a slightly more involved example, with an example of SwingBuilder code re-use via a closure.
http://docs.groovy-lang.org/latest/html/documentation/ 412/502
1/6/2019 Groovy Language Documentation
groovy.swing.
javax.swing.*
java.awt.*
swing = ()
sharedPanel = {
swing.panel() {
label("Shared Panel")
}
}
count = 0
swing.edt {
frame(title: 'Frame', defaultCloseOperation: .EXIT_ON_CLOSE, pack: , show: ) {
vbox {
textlabel = label('Click the button!')
button(
text: 'Click Me',
actionPerformed: {
count++
textlabel.text = "Clicked ${count} time(s)."
println "Clicked!"
}
)
widget(sharedPanel())
widget(sharedPanel())
}
}
}
groovy.swing.
groovy.beans.
{
@Bindable count = 0
}
model = ()
().edt {
frame(title: 'Java Frame', size: [100, 100], locationRelativeTo: , show: ) {
gridLayout(cols: 1, rows: 2)
label(text: bind(source: model, sourceProperty: 'count', converter: { v -> v? "Clicked $v
times": ''}))
button('Click me!', actionPerformed: { model.count++ })
}
}
@Bindable is one of the core AST Transformations. It generates all the required boilerplate code to turn a simple bean into an
observable one. The bind() node creates appropriate PropertyChangeListeners that will update the interested parties
whenever a PropertyChangeEvent is red.
AntBuilder
Despite being primarily a build tool, Apache Ant (http://ant.apache.org/) is a very practical tool for manipulating les including zip
les, copy, resource processing, … But if ever you’ve been working with a build.xml le or some Jelly script and found yourself a
little restricted by all those pointy brackets, or found it a bit weird using XML as a scripting language and wanted something a little
cleaner and more straight forward, then maybe Ant scripting with Groovy might be what you’re after.
Groovy has a helper class called AntBuilder which makes the scripting of Ant tasks really easy; allowing a real scripting language
to be used for programming constructs (variables, methods, loops, logical branching, classes etc). It still looks like a neat concise
version of Ant’s XML without all those pointy brackets; though you can mix and match this markup inside your script. Ant itself is a
collection of jar les. By adding them to your classpath, you can easily use them within Groovy as is. We believe using
AntBuilder leads to more concise and readily understood syntax.
http://docs.groovy-lang.org/latest/html/documentation/ 413/502
1/6/2019 AntBuilder exposes Ant tasks directly using the convenient builder
Groovy notation
Language that we are used to in Groovy. Here is the most
Documentation
basic example, which is printing a message on the standard output:
ant = () 1
Imagine that you need to create a ZIP le. It can be as simple as:
ant = ()
ant.zip(destfile: 'sources.zip', basedir: 'src')
In the next example, we demonstrate the use of AntBuilder to copy a list of les using a classical Ant pattern directly in Groovy:
Another example would be iterating over a list of les matching a speci c pattern:
ant.junit {
classpath { pathelement(path: '.') }
test(name:'some.pkg.MyTest')
}
We can even go further by compiling and executing a Java le directly from Groovy:
http://docs.groovy-lang.org/latest/html/documentation/ 414/502
1/6/2019 Groovy Language Documentation
ant.echo(file:'Temp.java', '''
class Temp {
public static void main(String[] args) {
System.out.println("Hello");
}
}
''')
ant.javac(srcdir:'.', includes:'Temp.java', fork:'true')
ant.java(classpath:'.', classname:'Temp', fork:'true')
ant.echo('Done')
It is worth mentioning that AntBuilder is included in Gradle (http://gradle.org/), so you can use it in Gradle just like you would in
Groovy. Additional documentation can be found in the Gradle manual (http://gradle.org/docs/current/userguide/ant.html).
CliBuilder
CliBuilder provides a compact way to specify the available options for a commandline application and then automatically parse
the application’s commandline parameters according to that speci cation. By convention, a distinction is made between option
commandline parameters and any remaining parameters which are passed to an application as its arguments. Typically, several
types of options might be supported such as -V or --tabsize=4 . CliBuilder removes the burden of developing lots of code
for commandline processing. Instead, it supports a somewhat declarative approach to declaring your options and then provides a
single call to parse the commandline parameters with a simple mechanism to interrogate the options (you can think of this as a
simple model for your options).
Even though the details of each commandline you create could be quite di erent, the same main steps are followed each time.
First, a CliBuilder instance is created. Then, allowed commandline options are de ned. This can be done using a dynamic api
style or an annotation style. The commandline parameters are then parsed according to the options speci cation resulting in a
collection of options which are then interrogated.
// specify parameters
cli = (usage: 'groovy Greeter [option]') 2
(options.h) cli.usage() 6
Earlier versions of Groovy had a CliBuilder in the groovy.util package and no import was necessary. While still supported,
this approach is now deprecated and you should instead choose the groovy.cli.picocli or groovy.cli.commons version. The
1
groovy.util version points to the commons-cli version for backwards compatibility but will be removed in a future version of
Groovy.
2 de ne a new CliBuilder instance specifying an optional usage string
3 specify a -a option taking a single argument with an optional long variant --audience
4 specify a -h option taking no arguments with an optional long variant --help
5 parse the commandline parameters supplied to the script
6 if the h option is found display a usage message
7 display a standard greeting or, if the a option is found, a customized greeting
> groovy
Hello World
http://docs.groovy-lang.org/latest/html/documentation/ 415/502
1/6/2019 Running this script with -h as the single commandline parameter, i.e.:
Groovy Language Documentation
> groovy -h
Running this script with --audience Groovologist as the commandline parameters, i.e.:
Hello Groovologist
When creating the CliBuilder instance in the above example, we set the optional usage property within the constructor call.
This follows Groovy’s normal ability to set additional properties of the instance during construction. There are numerous other
properties which can be set such as header and footer . For the complete set of available properties, see the available
properties for the CliBuilder (http://docs.groovy-lang.org/2.5.5/html/gapi/index.html?groovy/util/CliBuilder.html) class.
When de ning an allowed commandline option, both a short name (e.g. "h" for the help option shown previously) and a short
description (e.g. "display usage" for the help option) must be supplied. In our example above, we also set some additional
properties such as longOpt and args . The following additional properties are supported when specifying an allowed
commandline option:
If you have an option with only a longOpt variant, you can use the special shortname of '_' to specify the option, e.g. :
cli._(longOpt: 'verbose', 'enable verbose logging') . Some of the remaining named parameters should be fairly self-
explanatory while others deserve a bit more explanation. But before further explanations, let’s look at ways of using CliBuilder
with annotations.
http://docs.groovy-lang.org/latest/html/documentation/ 416/502
1/6/2019 Rather than making a series of method calls (albeit in a very declarative
Groovy Languagemini-DSL form) to specify the allowable options, you can
Documentation
provide an interface speci cation of the allowable options where annotations are used to indicate and provide details for those
options and for how unprocessed parameters are handled. Two annotations are used: groovy.cli.Option (http://docs.groovy-
lang.org/2.5.5/html/gapi/index.html?groovy/cli/Option.html) and groovy.cli.Unparsed (http://docs.groovy-
lang.org/2.5.5/html/gapi/index.html?groovy/cli/Unparsed.html).
{
@Option(shortName='h', description='display usage') help() 1
Note how the long name is automatically determined from the interface method name. You can use the longName annotation
attribute to override that behavior and specify a custom long name if you wish or use a longName of '_' to indicate that no long
name is to be provided. You will need to specify a shortName in such a case.
options.audience() == 'Groovologist' 3
options.help()
options.remaining() == ['Some', 'Other', 'Args'] 5
When parseFromSpec is called, CliBuilder automatically creates an instance implementing the interface and populates it. You
simply call the interface methods to interrogate the option values.
http://docs.groovy-lang.org/latest/html/documentation/ 417/502
1/6/2019 Groovy Language Documentation
{
@Option(shortName='h', description='display usage')
help 1
audience
@Option(shortName='a', description='greeting audience')
setAudience( audience) { 2
.audience = audience
}
getAudience() { audience }
options = () 2
options.audience == 'Groovologist' 4
options.remaining == ['foo'] 5
When parseFromInstance is called, CliBuilder automatically populates your instance. You simply interrogate the instance
properties (or whatever accessor methods you have provided in your domain object) to access the option values.
Here is an example using those annotations in a self-contained script that would be called with the same arguments as shown for
the instance example earlier:
@OptionField audience
@OptionField help
@UnparsedField remaining
().parseFromInstance( , args)
audience == 'Groovologist'
remaining == ['foo']
http://docs.groovy-lang.org/latest/html/documentation/ 418/502
1/6/2019 We saw in our initial example that some options act like Groovy
ags, e.g.Language -h but others take an argument, e.g.
GreeterDocumentation
Greeter --audience Groovologist . The simplest cases involve options which act like ags or have a single (potentially
optional) argument. Here is an example involving those cases:
options.a ==
options.b == 'foo'
options.c == 'bar'
options.arguments() == ['baz']
options.a ==
options.c ==
options.b == 'foo'
options.arguments() == ['bar', 'baz']
1 An option that is simply a ag - the default; setting args to 0 is allowed but not needed.
2 An option with exactly one argument
3 An option with an optional argument; it acts like a ag if the option is left out
4 An example using this spec where an argument is supplied to the 'c' option
5 An example using this spec where no argument is supplied to the 'c' option; it’s just a ag
Note: when an option with an optional argument is encountered, it will (somewhat) greedily consume the next parameter from
the supplied commandline parameters. If however, the next parameter matches a known long or short option (with leading single
or double hyphens), that will take precedence, e.g. -b in the above example.
Option arguments may also be speci ed using the annotation style. Here is an interface option speci cation illustrating such a
de nition:
{
@Option a()
@Option b()
@Option(optionalArg= ) [] c()
@Unparsed remaining()
}
cli = ()
options = cli.parseFromSpec( , '-a -b foo -c bar baz'.split())
options.a()
options.b() == 'foo'
options.c() == ['bar']
options.remaining() == ['baz']
This example makes use of an array-typed option speci cation. We cover this in more detail shortly when we discuss multiple
arguments.
Specifying a type
http://docs.groovy-lang.org/latest/html/documentation/ 419/502
1/6/2019 Arguments on the commandline are by nature Strings (or Groovy
arguably can be considered
Language Booleans for ags) but can be converted to
Documentation
richer types automatically by supplying additional typing information. For the annotation-based argument de nition style, these
types are supplied using the eld types for annotation properties or return types of annotated methods (or the setter argument
type for setter methods). For the dynamic method style of argument de nition a special 'type' property is supported which allows
you to specify a Class name.
When an explicit type is de ned, the args named-parameter is assumed to be 1 (except for Boolean-typed options where it is 0
by default). An explicit args parameter can still be provided if needed. Here is an example using types with the dynamic api
argument de nition style:
Primitives, numeric types, les, enums and arrays thereof, are supported (they are converted using
StringGroovyMethods#asType(String, Class) (http://docs.groovy-lang.org/2.5.5/html/gapi/index.html?
org/codehaus/groovy/runtime/StringGroovyMethods.html#asType)).
Alternatively, you can use the annotation style by supplying the conversion closure as an annotation parameter. Here is an
example speci cation:
{
@Option(convert={ it.toLowerCase() }) a()
@Option(convert={ it.toUpperCase() }) b()
@Option(convert={ .parse("yyyy-MM-dd", it) }) d()
@Unparsed remaining()
}
http://docs.groovy-lang.org/latest/html/documentation/ 420/502
1/6/2019 And an example using that speci cation: Groovy Language Documentation
The args value is normally an integer. It can be optionally supplied as a String. There are two special String symbols: + and * .
The * value means 0 or more. The + value means 1 or more. The * value is the same as using + and also setting the
optionalArg value to true.
Accessing the multiple arguments follows a special convention. Simply add an 's' to the normal property you would use to access
the argument option and you will retrieve all the supplied arguments as a list. So, for a short option named 'a', you access the rst
'a' argument using options.a and the list of all arguments using options.as . It’s ne to have a shortname or longname ending
in 's' so long as you don’t also have the singular variant without the 's'. So, if name is one of your options with multiple arguments
and guess is another with a single argument, there will be no confusion using options.names and options.guess .
options.a == '1' 4
options. == ['1', '2'] 5
options.arguments() == ['3', '4']
options = cli.parse(['-b1,2']) 7
options = cli.parse(['-c1'])
options.cs == ['1']
options = cli.parse(['-c1,2,3'])
options.cs == ['1', '2', '3']
As an alternative to accessing multiple arguments using the plural name approach, you can use an array-based type for the
option. In this case, all options will always be returned via the array which is accessed via the normal singular name. We’ll see an
example of this next when discussing types.
Multiple arguments are also supported using the annotation style of option de nition by using an array type for the annotated
class member (method or property) as this example shows:
{
@Option(numberOfArguments=2) [] a()
@Option(numberOfArgumentsString='2', valueSeparator=',') [] b()
@Option(numberOfArgumentsString='+', valueSeparator=',') [] c()
@Unparsed remaining()
}
cli = ()
1 For an array type, the trailing 's' can be used but isn’t needed
Here is how you could use it using the dynamic api style:
http://docs.groovy-lang.org/latest/html/documentation/ 422/502
1/6/2019 Groovy Language Documentation
cli = ()
cli.f longOpt: 'from', type: , args: 1, defaultValue: 'one', 'f option'
cli.t longOpt: 'to', type: , defaultValue: '35', 't option'
Similarly, you might want such a speci cation using the annotation style. Here is an example using an interface speci cation:
{
@Option(shortName='f', defaultValue='one') ()
@Option(shortName='t', defaultValue='35') to()
}
cli = ()
You can also use the defaultValue annotation attribute when using annotations with an instance, though it’s probably just as
easy to provide an initial value for the property (or backing eld).
{
@Option name()
@Option age()
@Unparsed remaining()
}
@TypeChecked
testTypeCheckedInterface() {
argz = "--name John --age 21 and some more".split()
cli = ()
options = cli.parseFromSpec( , argz)
n = options.name()
a = options.age()
n == 'John' && a == 21
options.remaining() == ['and', 'some', 'more']
}
http://docs.groovy-lang.org/latest/html/documentation/ 423/502
1/6/2019 Secondly, there is a feature of the dynamic api style whichGroovy
o ers some support.
Language The de nition statements are inherently dynamic
Documentation
but actually return a value which we have ignored in earlier examples. The returned value is in fact a TypedOption<Type> and
special getAt support allows the options to be interrogated using the typed option, e.g. options[savedTypeOption] . So, if you
have statements similar to these in a non type checked part of your code:
cli = ()
< > age = cli.a(longOpt: 'age', type: , 'some age option')
Then, the following statements can be in a separate part of your code which is type checked:
Finally, there is one additional convenience method o ered by CliBuilder to even allow the de nition part to be type checked.
It is a slightly more verbose method call. Instead of using the short name (the opt name) in the method call, you use a xed name
of option and supply the opt value as a property. You must also specify the type directly as shown in the following example:
groovy.cli.
groovy.transform.
@TypeChecked
testTypeChecked() {
cli = ()
< > name = cli.option( , opt: 'n', longOpt: 'name', 'name option')
< > age = cli.option( , longOpt: 'age', 'age option')
argz = "--name John --age 21 and some more".split()
options = cli.parse(argz)
n = options[name]
a = options[age]
n == 'John' && a == 21
options.arguments() == ['and', 'some', 'more']
}
org.apache.commons.cli.*
cli = ()
cli.f longOpt: 'from', 'f option'
cli.u longOpt: 'until', 'u option'
optionGroup = ()
optionGroup. {
addOption cli.option('o', [longOpt: 'output'], 'o option')
addOption cli.option('d', [longOpt: 'directory'], 'd option')
}
cli.options.addOptionGroup optionGroup
!cli.parse('-d -o'.split()) 1
http://docs.groovy-lang.org/latest/html/documentation/ 424/502
1/6/2019 1 Groovy
The parse will fail since only one option from a group Language
can be Documentation
used at a time.
Picocli
Below are some features available in the picocli version of CliBuilder .
When users of your application give invalid command line arguments, CliBuilder writes an error message and the usage help
message to the stderr output stream. It doesn’t use the stdout stream to prevent the error message from being parsed when
your program’s output is used as input for another process. You can customize the destination by setting the errorWriter to a
di erent value.
On the other hand, CliBuilder.usage() prints the usage help message to the stdout stream. This way, when users request
help (e.g. with a --help parameter), they can pipe the output to a utility like less or grep .
You can specify di erent writers for testing. Be aware that for backwards compatibility, setting the writer property to a di erent
value will set both the writer and the errorWriter to the speci ed writer.
ANSI colors
The picocli version of CliBuilder renders the usage help message in ANSI colors on supported platforms automatically. If desired
you can customize (http://picocli.info/#_usage_help_with_styles_and_colors) this. (An example follows below.)
As before, you can set the synopsis of the usage help message with the usage property. You may be interested in a small
improvement: if you only set the command name , a synopsis will be generated automatically, with repeating elements followed
by … and optional elements surrounded with [ and ] . (An example follows below.)
This property exposes a UsageMessageSpec object from the underlying picocli library, which gives ne-grained control over
various sections of the usage help message. For example:
cli = ()
cli.name = "myapp"
cli.usageMessage. {
headerHeading("@|bold,underline Header heading:|@%n")
header("Header 1", "Header 2") // before the synopsis
synopsisHeading("%n@|bold,underline Usage:|@ ")
descriptionHeading("%n@|bold,underline Description heading:|@%n")
description("Description 1", "Description 2") // after the synopsis
optionListHeading("%n@|bold,underline Options heading:|@%n")
footerHeading("%n@|bold,underline Footer heading:|@%n")
footer("Footer 1", "Footer 2")
}
cli.a('option a description')
cli.b('option b description')
cli.c(args: '*', 'option c description')
cli.usage()
http://docs.groovy-lang.org/latest/html/documentation/ 425/502
1/6/2019 Groovy Language Documentation
The parser property gives access to the picocli ParserSpec object that can be used to customize the parser behavior. See the
documentation (http://picocli.info/apidocs/picocli/CommandLine.Model.ParserSpec.html) for details.
Map options
Finally, if your application has options that are key-value pairs, you may be interested in picocli’s support for maps. For example:
java.util.concurrent.
java.util.concurrent. .DAYS
java.util.concurrent. .HOURS
cli = ()
cli.D(args: 2, valueSeparator: '=', 'the old way') 1
1 Previously, key=value pairs were split up into parts and added to a list
2 Picocli map support: simply specify Map as the type of the option
3 You can even specify the type of the map elements
4 To compare, let’s specify two key-value pairs for each option
5 Previously, all key-value pairs end up in a list and it is up to the application to work with this list
6 Picocli returns the key-value pairs as a Map
7 Both keys and values of the map can be strongly typed
ObjectGraphBuilder
ObjectGraphBuilder is a builder for an arbitrary graph of beans that follow the JavaBean convention. It is in particular useful for
creating test data.
http://docs.groovy-lang.org/latest/html/documentation/ 426/502
1/6/2019 Groovy Language Documentation
com.acme
{
name
address
employees = []
}
{
line1
line2
zip
state
}
{
name
employeeId
address
company
}
Then using ObjectGraphBuilder building a Company with three employees is as easy as:
builder = () 1
builder.classLoader = . .classLoader 2
builder.classNameResolver = "com.acme" 3
3.times {
employee(id: it.toString(), name: "Drone $it") { 5
address(line1:"Post street") 6
}
}
}
acme !=
acme
acme.name == 'ACME'
acme.employees.size() == 3
employee = acme.employees[0]
employee
employee.name == 'Drone 0'
employee.address
will try to match a node name into a Class , using a default ClassNameResolver strategy that requires a package name
then will create an instance of the appropriate class using a default NewInstanceResolver strategy that calls a no-arg
constructor
resolves the parent/child relationship for nested nodes, involving two other strategies:
RelationNameResolver will yield the name of the child property in the parent, and the name of the parent property in the
child (if any, in this case, Employee has a parent property aptly named company )
http://docs.groovy-lang.org/latest/html/documentation/ 427/502
1/6/2019 ChildPropertySetter will insert the child into theGroovy
parentLanguage
taking intoDocumentation
account if the child belongs to a Collection or not
(in this case employees should be a list of Employee instances in Company ).
All 4 strategies have a default implementation that work as expected if the code follows the usual conventions for writing
JavaBeans. In case any of your beans or objects do not follow the convention you may plug your own implementation of each
strategy. For example imagine that you need to build a class which is immutable:
@Immutable
{
name
age
}
ObjectGraphBuilder supports ids per node, meaning that you can store a reference to a node in the builder. This is useful when
multiple objects reference the same instance. Because a property named id may be of business meaning in some domain
models ObjectGraphBuilder has a strategy named IdentifierResolver that you may con gure to change the default name
value. The same may happen with the property used for referencing a previously saved instance, a strategy named
ReferenceResolver will yield the appropriate value (default is `refId'):
}
}
Its worth mentioning that you cannot modify the properties of a referenced bean.
JmxBuilder
See Working with JMX - JmxBuilder for details.
FileTreeBuilder
FileTreeBuilder (http://docs.groovy-lang.org/2.5.5/html/gapi/index.html?groovy/util/FileTreeBuilder.html) is a builder for
generating a le directory structure from a speci cation. For example, to create the following tree:
http://docs.groovy-lang.org/latest/html/documentation/ 428/502
1/6/2019 Groovy Language Documentation
src/
|--- main
| |--- groovy
| |--- Foo.groovy
|--- test
|--- groovy
|--- FooTest.groovy
tmpDir = .createTempDir()
fileTreeBuilder = (tmpDir)
fileTreeBuilder.dir('src') {
dir('main') {
dir('groovy') {
file('Foo.groovy', 'println "Hello"')
}
}
dir('test') {
dir('groovy') {
file('FooTest.groovy', 'class FooTest extends GroovyTestCase {}')
}
}
}
tmpDir = .createTempDir()
fileTreeBuilder = (tmpDir)
fileTreeBuilder.src {
main {
groovy {
'Foo.groovy'('println "Hello"')
}
}
test {
groovy {
'FooTest.groovy'('class FooTest extends GroovyTestCase {}')
}
}
}
This produces the same directory structure as above, as shown by these `assert`s:
http://docs.groovy-lang.org/latest/html/documentation/ 429/502
1/6/2019 Groovy Language Documentation
println server.getAttribute(beanName, 'Age')
server.setAttribute(beanName, ('Name', 'New name'))
[] = [5, 20]
[] signature = [ .TYPE, .TYPE]
println server.invoke(beanName, 'add', , signature)
Leverage Spring’s MBean annotation support to export your Groovy beans as MBeans
You can monitor the JVM through its platform MBeans with the following code:
http://docs.groovy-lang.org/latest/html/documentation/ 430/502
1/6/2019 Groovy Language Documentation
java.lang.management.*
os = .operatingSystemMXBean
println """OPERATING SYSTEM:
\tarchitecture = $os.arch
\tname = $os.name
\tversion = $os.version
\tprocessors = $os.availableProcessors
"""
rt = .runtimeMXBean
println """RUNTIME:
\tname = $rt.name
\tspec name = $rt.specName
\tvendor = $rt.specVendor
\tspec version = $rt.specVersion
\tmanagement spec version = $rt.managementSpecVersion
"""
cl = .classLoadingMXBean
println """CLASS LOADING SYSTEM:
\tisVerbose = ${cl.isVerbose()}
\tloadedClassCount = $cl.loadedClassCount
\ttotalLoadedClassCount = $cl.totalLoadedClassCount
\tunloadedClassCount = $cl.unloadedClassCount
"""
comp = .compilationMXBean
println """COMPILATION:
\ttotalCompilationTime = $comp.totalCompilationTime
"""
mem = .memoryMXBean
heapUsage = mem.heapMemoryUsage
nonHeapUsage = mem.nonHeapMemoryUsage
println """MEMORY:
HEAP STORAGE:
\tcommitted = $heapUsage.committed
\tinit = $heapUsage.init
\tmax = $heapUsage.max
\tused = $heapUsage.used
NON-HEAP STORAGE:
\tcommitted = $nonHeapUsage.committed
\tinit = $nonHeapUsage.init
\tmax = $nonHeapUsage.max
\tused = $nonHeapUsage.used
"""
.memoryPoolMXBeans.each { mp ->
println "\tname: " + mp.name
[] mmnames = mp.memoryManagerNames
mmnames.each{ mmname ->
println "\t\tManager Name: $mmname"
}
println "\t\tmtype = $mp.type"
println "\t\tUsage threshold supported = " + mp.isUsageThresholdSupported()
}
println()
td = .threadMXBean
println "THREADS:"
td.allThreadIds.each { tid ->
println "\tThread name = ${td.getThreadInfo(tid).threadName}"
}
println()
http://docs.groovy-lang.org/latest/html/documentation/ 432/502
1/6/2019 Groovy Language Documentation
OPERATING SYSTEM:
architecture = x86
name = Windows XP
version = 5.1
processors = 2
RUNTIME:
name = 620@LYREBIRD
spec name = Java Virtual Machine Specification
vendor = Sun Microsystems Inc.
spec version = 1.0
management spec version = 1.0
COMPILATION:
totalCompilationTime = 91
MEMORY:
HEAP STORAGE:
committed = 3108864
init = 0
max = 66650112
used = 1994728
NON-HEAP STORAGE:
committed = 9240576
init = 8585216
max = 100663296
used = 5897880
THREADS:
Thread name = Monitor Ctrl-Break
Thread name = Signal Dispatcher
Thread name = Finalizer
Thread name = Reference Handler
Thread name = main
GARBAGE COLLECTION:
name = Copy
collection count = 60
collection time = 141
http://docs.groovy-lang.org/latest/html/documentation/ 433/502
1/6/2019 mpool name = Eden Space Groovy Language Documentation
mpool name = Survivor Space
name = MarkSweepCompact
collection count = 0
collection time = 0
mpool name = Eden Space
mpool name = Survivor Space
mpool name = Tenured Gen
mpool name = Perm Gen
You can do this in your startup script and may choose any available port, we used 9004.
The following code uses JMX to discover the available MBeans in the running Tomcat, determine which are web modules, extract
the processing time for each web module and displays the result in a graph using JFreeChart:
groovy.swing.
javax.management.
javax.management.remote.
javax.management.remote.
javax.swing. WC
org.jfree.chart.
org.jfree.data.category.
org.jfree.chart.plot.
serverUrl = 'service:jmx:rmi:///jndi/rmi://localhost:9004/jmxrmi'
server = .connect( (serverUrl)).
serverInfo = (server, 'Catalina:type=Server').serverInfo
println "Connected to: $serverInfo"
query = ('Catalina:*')
[] allNames = server.queryNames(query, )
modules = allNames.findAll { name ->
name.contains('j2eeType=WebModule')
}.collect{ (server, it) }
modules.each { m ->
println m.name()
dataset.addValue m.processingTime, 0, m.path
}
Note: if you get errors running this script, see the Troubleshooting section below.
javax.management.remote.*
oracle.oc4j.admin.jmx.remote.api.
serverUrl = ('service:jmx:rmi://localhost:23791')
serverPath = 'oc4j:j2eeType=J2EEServer,name=standalone'
jvmPath = 'oc4j:j2eeType=JVM,name=single,J2EEServer=standalone'
provider = 'oracle.oc4j.admin.jmx.remote'
credentials = [
( .CREDENTIALS_LOGIN_KEY): 'oc4jadmin',
( .CREDENTIALS_PASSWORD_KEY): 'admin'
]
env = [
( .PROTOCOL_PROVIDER_PACKAGES): provider,
( .CREDENTIALS): credentials
]
server = .connect(serverUrl, env).
serverInfo = (server, serverPath)
jvmInfo = (server, jvmPath)
println """Connected to $serverInfo.node. \
Server started ${new Date(serverInfo.startTime)}.
OC4J version: $serverInfo.serverVersion from $serverInfo.serverVendor
JVM version: $jvmInfo.javaVersion from $jvmInfo.javaVendor
Memory usage: $jvmInfo.freeMemory bytes free, \
$jvmInfo.totalMemory bytes total
"""
As a slight variation, this script displays a pie chart of memory usage using JFreeChart:
org.jfree.chart.
javax.swing. WC
javax.management.remote.*
oracle.oc4j.admin.jmx.remote.api.
url = 'service:jmx:rmi://localhost:23791'
credentials = [:]
credentials[ .CREDENTIALS_LOGIN_KEY] = "oc4jadmin"
credentials[ .CREDENTIALS_PASSWORD_KEY] = "password"
env = [:]
env[ .PROTOCOL_PROVIDER_PACKAGES] = "oracle.oc4j.admin.jmx.remote"
env[ .CREDENTIALS] = credentials
server = .connect( (url), env).
jvmInfo = (server, 'oc4j:j2eeType=JVM,name=single,J2EEServer=standalone')
piedata = org.jfree.data.general. ()
piedata.setValue "Free", jvmInfo.freeMemory
piedata.setValue "Used", jvmInfo.totalMemory - jvmInfo.freeMemory
options = [ , , ]
chart = .createPieChart('OC4J Memory Usage', piedata, *options)
chart.backgroundPaint = java.awt. .white
swing = groovy.swing. ()
frame = swing.frame(title:'OC4J Memory Usage', defaultCloseOperation:WC.EXIT_ON_CLOSE) {
panel(id:'canvas') { rigidArea(width:350, height:250) }
}
frame.pack()
frame.show()
chart.draw(swing.canvas.graphics, swing.canvas.bounds)
http://docs.groovy-lang.org/latest/html/documentation/ 436/502
1/6/2019 Groovy Language Documentation
javax.management.remote.*
javax.management.*
javax.naming.
urlRuntime = '/jndi/weblogic.management.mbeanservers.runtime'
urlBase = 'service:jmx:t3://localhost:7001'
Server: name=examplesServer, state=RUNNING, version=WebLogic Server 10.0 Wed May 9 18:10:27 EDT
2007 933139
JMS Destination: name=examples-jms!exampleTopic, type=Topic, messages=0
JMS Destination: name=examples-jms!exampleQueue, type=Queue, messages=0
JMS Destination: name=examples-jms!jms/MULTIDATASOURCE_MDB_QUEUE, type=Queue, messages=0
JMS Destination: name=examplesJMSServer!examplesJMSServer.TemporaryQueue0, type=Queue, messages=68
JMS Destination: name=examples-jms!quotes, type=Topic, messages=0
JMS Destination: name=examples-jms!weblogic.wsee.wseeExamplesDestinationQueue, type=Queue,
messages=0
JMS Destination: name=examples-jms!weblogic.examples.ejb30.ExampleQueue, type=Queue, messages=0
http://docs.groovy-lang.org/latest/html/documentation/ 437/502
1/6/2019 Groovy Language Documentation
org.springframework.jmx. .annotation.*
invocations
= 10
http://docs.groovy-lang.org/latest/html/documentation/ 438/502
1/6/2019 Groovy Language Documentation
<?xml version="1.0" encoding="UTF-8"?>
xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-
beans.xsd"
id="mbeanServer"
class="org.springframework.jmx.support.MBeanServerFactoryBean"
name="locateExistingServerIfPossible" value="true"
id="exporter"
class="org.springframework.jmx.export.MBeanExporter"
name="assembler" ref="assembler"
name="namingStrategy" ref="namingStrategy"
name="beans"
key="bean:name=defaultCalcName" value-ref="calcBean"
name="server" ref="mbeanServer"
name="autodetect" value="true"
id="jmxAttributeSource"
class="org.springframework.jmx.export.annotation.AnnotationJmxAttributeSource"
id="calcBean"
class="Calculator"
name="base" value="10"
http://docs.groovy-lang.org/latest/html/documentation/ 439/502
1/6/2019 Groovy Language Documentation
org.springframework.context.support.
java.lang.management.
javax.management.
javax.management.
.start {
// access bean via JMX, use a separate thread just to
// show that we could access remotely if we wanted
server = .platformMBeanServer
mbean = (server, 'bean:name=calcMBean')
sleep 1000
8 == mbean.add(7, 1)
mbean. = 8
'10' == mbean.addStrings('7', '1')
mbean. = 16
sleep 2000
println "Number of invocations: $mbean.Invocations"
println mbean
}
15 == calc.add(9, 6)
'11' == calc.addStrings('10', '1')
sleep 2000
'20' == calc.addStrings('1f', '1')
Number of invocations: 5
MBean Name:
bean:name=calcMBean
Attributes:
(rw) int Base
(r) int Invocations
Operations:
int add(int x, int y)
java.lang.String addStrings(java.lang.String x, java.lang.String y)
int getInvocations()
int getBase()
void setBase(int p1)
You can even attach to the process while it is running with jconsole
(http://docs.oracle.com/javase/1.5.0/docs/guide/management/jconsole.html). It will look something like:
http://docs.groovy-lang.org/latest/html/documentation/ 440/502
1/6/2019 Groovy Language Documentation
See also:
3.16.7. Troubleshooting
java.lang.SecurityException
If you get the following error, your container’s JMX access is password protected:
To x that, add an environment with the credentials when connecting, like this (password has to be set before that):
jmxEnv =
(password != ) {
jmxEnv = [( .CREDENTIALS): ( [])["monitor", password]]
}
connector = .connect( (serverUrl), jmxEnv)
Details for the software you are trying to monitor/manage may di er slightly. Check out the other examples using credentials
above if appropriate (e.g. OC4J and WebLogic). If you still have troubles, you will have to consult the documentation for the
software you are trying to monitor/manage for details on how to provide credentials.
3.16.8. JmxBuilder
JmxBuilder is a Groovy-based domain speci c language for the Java Management Extension (JMX) API. It uses the builder
pattern (FactoryBuilder) to create an internal DSL that facilitates the exposure of POJO’s and Groovy beans as management
components via the MBean server. JmxBuilder hides the complexity of creating and exporting management beans via the JMX API
and provides a set of natural Groovy constructs to interact with the JMX infrastructure.
Instantiating JmxBuilder
To start using JmxBuilder, simply make sure the jar le is on your class path. Then you can do the following in your code:
http://docs.groovy-lang.org/latest/html/documentation/ 441/502
1/6/2019 Groovy Language Documentation
jmx = ()
NOTE
You can pass in an instance of your own MBeanServer to the builder (JmxBuilder(MBeanServer))
If no MBeanServer is speci ed, the builder instance will default to the underlying platform MBeanServer.
Once you have an instance of JmxBuilder, you are now ready to invoke any of its builder nodes.
JMX Connectors
Remote connectivity is a crucial part of the JMX architecture. JmxBuilder facilitates the creation of connector servers and
connector clients with a minimal amount of coding.
Connector Server
JmxBuilder.connectorServer() supports the full Connector api syntax and will let you specify properties, override the URL, specify
your own host, etc.
Syntax
jmx.connectorServer(
protocol:"rmi",
host:"...",
port:1099,
url:"...",
properties:[
"authenticate":true|false,
"passwordFile":"...",
"accessFile":"...",
"sslEnabled" : true | false
// any valid connector property
]
)
Note that the serverConnector node will accept four ServerConnector property aliases (authenticate, passwordFile,accessFile, and
sslEnabled). You can use these aliases or provided any of the RMI-supported properties.
jmx.connectorServer(port: 9000).start()
The snippet above returns an RMI connector that will start listening on port 9000. By default, the builder will internally generate
URL "service:jmx:rmi:///jndi/rmi://localhost:9000/jmxrmi".
NOTE: Sadly you are as likely to get something like the following when attempting to run the previous snippet of code (example is
incomplete, see below):
This occurs on Mac and Linux (CentOS 5) with Groovy 1.6 installed. Perhaps there were assumptions made about the
con guration of the /etc/hosts le?
http://docs.groovy-lang.org/latest/html/documentation/ 442/502
1/6/2019 The example above does not create the RMI registry. So, in order Language
Groovy to export,Documentation
you have to rst export the RMI object registry (make
sure to import java.rmi.registry.LocateRegistry ).
java.rmi.registry.
//...
.createRegistry(9000)
jmx.connectorServer(port: 9000).start()
Connector Client
JmxBuilder.connectorClient() node lets you create JMX connector client object to connect to a JMX MBean Server.
Syntax
jmx.connectorClient (
protocol:"rmi",
host:"...",
port:1099,
url:"...",
)
Creating a connector client can be done just as easily. With one line of code, you can create an instance of a JMX Connector Client
as shown below.
You can then access the MBeanServerConnection associated with the connector using:
client.getMBeanServerConnection()
beans = jmx. {
bean( ())
bean( ())
bean( ())
}
In the code snippet above, JmxBuilder.export() will export three management beans to the MBean server.
JmxBuilder.export() Syntax
JmxBuilder.export() node supports the registrationPolicy parameter to specify how JmxBuilder will behave to resolve bean name
collision during MBean registration:
http://docs.groovy-lang.org/latest/html/documentation/ 443/502
1/6/2019 Groovy Language Documentation
jmx.export(policy:"replace|ignore|error")
or
jmx.export(regPolicy:"replace|ignore|error")
replace - JmxBuilder.export() will replace any bean already registered with the MBean during export.
ignore - The bean being exported will be ignored if the same bean is already registered.
error - JmxBuilder.export() throws an error upon bean name collision during registration.
RequestController
{
// constructors
() { () }
( resource) { }
// attributes
isStarted() { }
getRequestCount() { 0 }
getResourceCount() { 0 }
setRequestLimit( limit) { }
getRequestLimit() { 0 }
// operations
start() { }
stop() { }
putResource( name, resource) { }
makeRequest( res) { }
makeRequest() { }
}
Implicit Export
As mentioned earlier, you can use JmxBuilder’s exible syntax to export any POJO/POGO with no descriptor. The builder can
automatically describe all aspects of the management beans using implicit defaults. These default values can easily be overridden
as we’ll see in this in the next section.
jmx. {
bean( (resource: "Hello World"))
}
First, the JmxBuilder.export() node will export an MBean to the MBeanServer representing the declared POJO instance.
The builder will generate a default ObjectName for the MBean and all other MBean descriptor information.
JmxBuilder will automatically export all declared attributes (MBean getter/setters), constructors, and operations on the
instance.
Remember, JmxBuilder.export() returns an array of GroovyMBean[] objects for all exported instances. So, once you call
JmxBuilder.export(), you have immediate access to the underlying MBean proxy (via GroovyMBean).
http://docs.groovy-lang.org/latest/html/documentation/ 444/502
1/6/2019 JConsole view of Exported Bean Groovy Language Documentation
JmxBuilder.bean() Syntax
The JmxBuilder.bean() node supports an extensive set of descriptors to describe your bean for management. The JMX
MBeanServer uses these descriptors to expose meta data about the bean exposed for management.
http://docs.groovy-lang.org/latest/html/documentation/ 445/502
1/6/2019 Groovy Language Documentation
jmx.export {
bean(
target:bean instance,
name:ObjectName,
desc:"...",
attributes:"*",
attributes:[]
attributes:[ "AttrubuteName1","AttributeName2",...,"AttributeName_n" ]
attributes:[
"AttributeName":"*",
"AttributeName":[
desc:"...",
defaultValue:value,
writable:true|false,
editable:true|false,
onChange:{event-> // event handler}
]
],
constructors:"*",
constructors:[
"Constructor Name":[],
"Constructor Name":[ "ParamType1","ParamType2,...,ParamType_n" ],
"Constructor Name":[
desc:"...",
params:[
"ParamType1":"*",
"ParamType2":[desc:"...", name:"..."],...,
"ParamType_n":[desc:"...", name:"..."]
]
]
],
operations:"*",
operations:[ "OperationName1", "OperationName2",...,"OperationNameN" ],
operations:[
"OperationName1":"*",
"OperationName2":[ "type1","type2,"type3" ]
"OperationName3":[
desc:"...",
params:[
"ParamType1":"*"
"ParamType2":[desc:"...", name:"..."],...,
"ParamType_n":[desc:"...", name:"..."]
],
onInvoked:{event-> JmxBuilder.send(event:"", to:"")}
]
],
listeners:[
"ListenerName1":[event: "...", from:ObjectName, call:{event->}],
"ListenerName2":[event: "...", from:ObjectName, call:&methodPointer]
]
)
}
Instead of describing the entire node, the following section explore each attribute separately.
objName = ("jmx.tutorial:type=Object")
beans = jmx. {
bean(target: (),
name: objName,
attributes: "*")
}
objName = ("jmx.tutorial:type=Object")
beans = jmx. {
bean(
target: (),
name: objName,
attributes: ["Resource", "RequestCount"]
)
}
In the snippet above, only the "Resource" and "RequestCount" attributes will be exported. Again, since no descriptors are
provided, JmxBuilder will use sensible defaults to describe the exported attributes.
objName = ("jmx.tutorial:type=Object")
beans = jmx. {
bean(
target: (),
name: objName,
attributes: [
"Resource": [desc: "The resource to request.", readable: , writable: ,
defaultValue: "Hello"],
"RequestCount": "*"
]
)
}
In the snippet above, attribute "Resource" is fully-described using all supported descriptors (i.e. desc, readable, writable,
defaultValue) for a JMX attribute. However, we use the wildcard to describe attribute RequestCount and it will be exported and
described using defaults.
objName = ("jmx.tutorial:type=Object")
beans = jmx. {
bean(
target: (),
name: objName,
constructors: [
"RequestController": ["Object"]
]
)
}
Here, JmxBuilder will export a constructor that takes one parameter of type "Object". Again, JmxBuilder will use default values
to ll in the description of the constructor and the parameters.
objName = ("jmx.tutorial:type=Object")
beans = jmx. {
bean(target: (), name: objName,
constructors: [
"RequestController": [
desc: "Constructor takes param",
: ["Object" : [name: "Resource", desc: "Resource for controller"]]
]
]
)
}
In the code above, JmxBuilder will target a constructor that takes one parameter for export to the MBeanServer. Notice how the
constructor can be fully-described using all optional descriptor keys including parameter descriptors.
objName = ("jmx.tutorial:type=Object")
beans = jmx. {
bean(
target: (),
name: objName,
operations: "*"
)
}
http://docs.groovy-lang.org/latest/html/documentation/ 448/502
1/6/2019 In this snippet, JmxBuilder will export all bean operationsGroovy
and will use default
Language values to describe them in the MBeanServer.
Documentation
objName = ("jmx.tutorial:type=Object")
beans = jmx. {
bean(
target: (),
name: objName,
operations: ["start", "stop"]
)
}
In the snippet above, the builder will only export methods start() and stop(). All other methods will be ignored. JmxBuilder will
use default descriptor values to describe the operations being exported.
objName = ("jmx.tutorial:type=Object")
beans = jmx. {
bean(
target: (),
name: objName,
operations: [
"makeRequest": ["String"]
]
)
}
In the snippet above, JmxBuilder would select method makeRequest(String) to be exported instead of the other version
makeRequest() which takes no parameter. In this shorthand context, the signature is speci ed as a list of type (i.e. "String").
objName = ("jmx.tutorial:type=Object")
beans = jmx. {
bean(target: (), name: objName,
operations: [
"start": [desc: "Starts request controller"],
"stop": [desc: "Stops the request controller"],
"setResource": [ : ["Object"]],
"makeRequest": [
desc: "Executes the request.",
: [
"String": [name: "Resource", desc: "The resource to request"]
]
]
]
)
}
The snippet above shows all of the ways JmxBuilder allows you to describe an operation targeted for management:
Operations start() and stop() are described by the "desc" key (this is enough since there are no params).
In operation setResource() uses of a shorthand version of params: to describe the parameters for the method.
makeRequest() uses the the extended descriptor syntax to describe all aspects of the operation.
http://docs.groovy-lang.org/latest/html/documentation/ 449/502
1/6/2019 Embedding Descriptor Groovy Language Documentation
JmxBuilder supports the ability to embed descriptors directly in your Groovy class. So, instead of wrapping your description
around the declared object (as we’ve seen here), you can embed your JMX descriptors directly in your class.
RequestControllerGroovy
{
// attributes
started
requestCount
resourceCount
requestLimit
resources
// operations
start() { }
stop(){ }
putResource( name, resource) { }
makeRequest( res) { }
makeRequest() { }
descriptor = [
name: "jmx.builder:type=EmbeddedObject",
operations: ["start", "stop", "putResource"],
attributes: "*"
]
}
// export
jmx. (
bean( ())
)
Groovy class RequestControllerGroovy is de ned and includes a static descriptor member. That member is used to declare a
JmxBuilder descriptor to describe member of the class targeted for JMX export.
The second part of the code shows how to use JmxBuilder to export that class for management.
Timer Export
JMX standards mandate that the implementation of the API makes available a timer service. Since JMX is a component-based
architecture, timers provide an excellent signalling mechanism to communicate to registered listener components in the
MBeanServer. JmxBuilder supports the creation and export of timers using the same easy syntax we’ve seen so far.
timer(
name:ObjectName,
event:"...",
message:"...",
data:dataValue
startDate:"now"|dateValue
period:"99d"|"99h"|"99m"|"99s"|99
occurrences:long
)
name: - Required The quali ed JMX ObjectName instance (or String) for the timer.
event: - The JMX event type string that will be broadcast with every timing signal (default "jmx.builder.event").
startDate: - When to start timer. Set of valid values [ "now", date object ]. Default is "now"
http://docs.groovy-lang.org/latest/html/documentation/ 450/502
1/6/2019 period: - A timer’s period expressed as either a number of millisecond
Groovy LanguageorDocumentation
time unit (day, hour, minute, second). See description
below.
occurrences: - A number indicating the number of time to repeat timer. Default is forever.
Exporting a Timer
This snippet above describes, creates, and exports a standard JMX Timer component. Here, the timer() node returns a
GroovyMBean that represents the registered timer MBean in the MBeanServer.
beans = jmx. {
timer(name: "jmx.builder:type=Timer1", : "event.signal", period: "1s")
timer(name: "jmx.builder:type=Timer2", : "event.log", period: "1s")
}
beans[0].start()
beans[1].start()
Timer Period
The timer() node supports a exible notation for specifying the timer period values. You can specify the time in second, minutes,
hour, and day. The default is millisecond.
Parameterless
callback = { ->
// event handling code here.
}
JmxBuilder executes the closure and passes no information about the event that was captured on the bus.
callback = { ->
// event handling code
}
JmxBuilder will pass an "event" object to the closure using this format. The event object contains information about the event
was intercepted so that it can be handled by the handler. The parameter will contain di erent set of info depending on the event
that was captured.
jmx. {
bean(
target: (), name: "jmx.tutorial:type=Object",
attributes: [
"Resource": [
readable: , writable: ,
onChange: { e ->
println e.oldValue
println e.newValue
}
]
]
)
}
The sample snippet above shows how to specify an "onChange" callback closure when describing MBean attributes. In this
sample code, whenever attribute "Resource" is updated via the exported MBean, the onChange event will be executed.
event.attributeType - the data type of the attribute that causes the event.
{
handleStart(e){
println e
}
}
handler = ()
beans = jmx. {
bean(target: (), name: "jmx.tutorial:type=Object",
operations: [
"start": [
desc:"Starts request controller",
onCall:handler.&handleStart
]
]
)
}
The snippet above shows how to declare an "onCall" closure to be used as listener when operation "start()" is invoked on the
MBean. This sample uses the method pointer syntax to illustrate the versatility of JmxBuilder.
http://docs.groovy-lang.org/latest/html/documentation/ 452/502
1/6/2019 event.event - the event type string that was broadcasted.
Groovy Language Documentation
event.data - the data type of the attribute that causes the event.
Listener MBean
When you export an MBean with the bean() node, you can de ne events the MBean can listen and react to. The bean() node
provides a "listeners:" attribute that lets you de ne event listeners that your bean can react to.
beans = jmx. {
timer(name: "jmx.builder:type=Timer", : "heartbeat", period: "1s").start()
bean(target: (), name: "jmx.tutorial:type=Object",
operations: "*",
listeners: [
heartbeat: [
: "jmx.builder:type=Timer",
call: { e ->
println e
}
]
]
)
}
In the sample above, we see the syntax for adding listeners to an exported MBean.
Then an MBean is declared that will listen to the timer event and do something meaningful.
The "heartbeat:" name is arbitrary and has no correlation to the timer declared above.
You can also specify an event type you are interested in receiving from a broadcaster (since a broadcaster can be emitting
multiple events).
jmx.listener(
event: "...",
from: "object name" | ObjectName,
call: { event-> }
)
event: An optional string that identi es the JMX event type to listen for.
from (required): The JMX ObjectName of the component to listen to. This can be speci ed as a string or an instance of
ObjectName
call: The closure to execute when the event is captured. This can also be speci ed as a Groovy method pointer.
http://docs.groovy-lang.org/latest/html/documentation/ 453/502
1/6/2019 Groovy Language Documentation
jmx.timer(name: "jmx.builder:type=Timer", period: "1s").start()
jmx.listener(
: "jmx.builder:type=Timer",
call: { e ->
println "beep..."
}
)
This example shows how you can use a stand alone listener (outside of an MBean export). Here, we export a timer with a 1
second resolution. Then, we specify a listener to that timer that will print "beep" every second.
Emitter Syntax
jmx.emitter(name:"Object:Name", event:"type")
name: an optional JMX ObjectName used to register your emitter in the MBeanServer. Default is
jmx.builder:type=Emitter,name=Emitter@OBJECT_HASH_VALUE
event: an option string value that describes the JMX event type. Default is "jmx.builder.event.emitter".
emitter = jmx.emitter()
The snippet declares the emitter using implicit descriptor syntax. JmxBuilder will do the followings:
As with other nodes in the builder, you can override all keys in the emitter() node. You can specify the ObjectName and the
event type.
Broadcast Event
Once you have declared your emitter, you can broadcast your event.
emitter.send()
The sample above shows the emitter sending an event, once it has been declared. Any JMX component registered in the
MBeanServer can register to receive message from this emitter.
emitter.send("Hello!")
If you use an event listener closure (see above) that accepts a parameter, you can access that value.
http://docs.groovy-lang.org/latest/html/documentation/ 454/502
1/6/2019 JMX Scripts with Eclipse Monkey (http://jmesnil.net/weblog/2007/05/23/jmx-scripts-with-eclipse-monkey)
Groovy Language Documentation
3.18. Security
(TBD)
some patterns carry over directly (and can make use of normal Groovy syntax improvements for greater readability)
some patterns are no longer required because they are built right into the language or because Groovy supports a better way
of achieving the intent of the pattern
some patterns that have to be expressed at the design level in other languages can be implemented directly in Groovy (due to
the way Groovy can blur the distinction between design and implementation)
3.19.1. Patterns
As an example, I might have interfaces Button, TextField and Scrollbar. I might have WindowsButton, MacButton, FlashButton as
concrete classes for Button. I might have WindowsScrollBar, MacScrollBar and FlashScrollBar as concrete implementations for
ScrollBar. Using the Abstract Factory Pattern should allow me to select which windowing system (i.e. Windows, Mac, Flash) I want
to use once and from then on should be able to write code that references the interfaces but is always using the appropriate
concrete classes (all from the one windowing system) under the covers.
Example
Suppose we want to write a game system. We might note that many games have very similar features and control.
We decide to try to split the common and game-speci c code into separate classes.
First let’s look at the game-speci c code for a Two-up (http://en.wikipedia.org/wiki/Two-Up) game:
http://docs.groovy-lang.org/latest/html/documentation/ 455/502
1/6/2019 Groovy Language Documentation
{
welcome = 'Welcome to the twoup game, you start with $1000'
= 'Sorry, you have no money left, goodbye'
}
{
convert(input) { input.toInteger() }
}
{
money = 1000
random = ()
tossWasHead() {
= random.nextInt()
% 2 == 0
}
moreTurns() {
(money > 0) {
println "You have $money, how much would you like to bet?"
}
play(amount) {
coin1 = tossWasHead()
coin2 = tossWasHead()
(coin1 && coin2) {
money += amount
println 'You win'
} (!coin1 && !coin2) {
money -= amount
println 'You lose'
} {
println 'Draw'
}
}
}
Now, let’s look at the game-speci c code for a number guessing game:
http://docs.groovy-lang.org/latest/html/documentation/ 456/502
1/6/2019 Groovy Language Documentation
{
welcome = 'Welcome to the guessing game, my secret number is between 1 and 100'
= 'Correct'
}
{
convert(input) { input.toInteger() }
}
{
lower = 1
upper = 100
guess = ().nextInt(upper - lower) + lower
moreTurns() {
= (lower == guess || upper == guess)
(! ) {
println "Enter a number between $lower and $upper"
}
!
}
play(nextGuess) {
(nextGuess <= guess) {
lower = [lower, nextGuess].max()
}
(nextGuess >= guess) {
upper = [upper, nextGuess].min()
}
}
}
{
factory
getMessages() { factory.messages.newInstance() }
getControl() { factory.control.newInstance() }
getConverter() { factory.converter.newInstance() }
}
The important aspect of this factory is that it allows selection of an entire family of concrete classes.
.factory = twoupFactory
messages = .messages
control = .control
converter = .converter
println messages.welcome
reader = ( ( . ))
(control.moreTurns()) {
input = reader.readLine().trim()
control.play(converter.convert(input))
}
println messages.
Note that the rst line con gures which family of concrete game classes we will use. It’s not important that we selected which
family to use by using the factory property as shown in the rst line. Other ways would be equally valid examples of this pattern.
For example, we may have asked the user which game they wanted to play or determined which game from an environment
setting.
http://docs.groovy-lang.org/latest/html/documentation/ 457/502
1/6/2019 With the code as shown, the game might look like this when run: Language Documentation
Groovy
If we change the rst line of the script to GameFactory.factory = guessFactory, then the sample run might look like this:
Adapter Pattern
The Adapter Pattern (http://en.wikipedia.org/wiki/Adapter_pattern) (sometimes called the wrapper pattern) allows objects
satisfying one interface to be used where another type of interface is expected. There are two typical avours of the pattern: the
delegation avour and the inheritance avour.
Delegation Example
Suppose we have the following classes:
{
width
}
{
radius
}
{
radius
pegFits(peg) {
peg.radius <= radius
}
toString() { "RoundHole with radius $radius" }
}
We can ask the RoundHole class if a RoundPeg ts in it, but if we ask the same question for a SquarePeg , then it will fail because
the SquarePeg class doesn’t have a radius property (i.e. doesn’t satisfy the required interface).
To get around this problem, we can create an adapter to make it appear to have the correct interface. It would look like this:
http://docs.groovy-lang.org/latest/html/documentation/ 458/502
1/6/2019 Groovy Language Documentation
{
peg
getRadius() {
.sqrt(((peg.width / 2) ** 2) * 2)
}
toString() {
"SquarePegAdapter with peg width $peg.width (and notional radius $radius)"
}
}
peg SquarePegAdapter with peg width 4 (and notional radius 2.8284271247461903) fits in hole
RoundHole with radius 4.0
peg SquarePegAdapter with peg width 5 (and notional radius 3.5355339059327378) fits in hole
RoundHole with radius 4.0
peg SquarePegAdapter with peg width 6 (and notional radius 4.242640687119285) does not fit in hole
RoundHole with radius 4.0
peg SquarePegAdapter with peg width 7 (and notional radius 4.949747468305833) does not fit in hole
RoundHole with radius 4.0
Inheritance Example
Let’s consider the same example again using inheritance. First, here are the original classes (unchanged):
{
width
}
{
radius
}
{
radius
pegFits(peg) {
peg.radius <= radius
}
toString() { "RoundHole with radius $radius" }
}
{
getRadius() {
.sqrt(((width / 2) ** 2) * 2)
}
toString() {
"SquarePegAdapter with width $width (and notional radius $radius)"
}
}
http://docs.groovy-lang.org/latest/html/documentation/ 459/502
1/6/2019 Using the adapter: Groovy Language Documentation
The output:
peg SquarePegAdapter with width 4 (and notional radius 2.8284271247461903) fits in hole RoundHole
with radius 4.0
peg SquarePegAdapter with width 5 (and notional radius 3.5355339059327378) fits in hole RoundHole
with radius 4.0
peg SquarePegAdapter with width 6 (and notional radius 4.242640687119285) does not fit in hole
RoundHole with radius 4.0
peg SquarePegAdapter with width 7 (and notional radius 4.949747468305833) does not fit in hole
RoundHole with radius 4.0
{
getRadius()
}
adapter = {
p -> [getRadius: { .sqrt(((p.width / 2) ** 2) * 2) }]
}
peg = (width: 4)
(hole.pegFits(adapter(peg))) {
// ... as before
}
peg = (width: 4)
peg.metaClass.radius = .sqrt(((peg.width / 2) ** 2) * 2)
After you create a peg object, you can simply add a property to it on the y. No need to change the original class and no need for
an adapter class.
Bouncer Pattern
The Bouncer Pattern (http://www.c2.com/cgi/wiki?BouncerPattern) describes usage of a method whose sole purpose is to either
throw an exception (when particular conditions hold) or do nothing. Such methods are often used to defensively guard pre-
conditions of a method.
http://docs.groovy-lang.org/latest/html/documentation/ 460/502
1/6/2019 When writing utility methods, you should always guard against
Groovyfaulty input Documentation
Language arguments. When writing internal methods, you may
be able to ensure that certain pre-conditions always hold by having su cient unit tests in place. Under such circumstances, you
may reduce the desirability to have guards on your methods.
Groovy di ers from other languages in that you frequently use the assert method within your methods rather than having a
large number of utility checker methods or classes.
{
check(name, arg) {
(arg == ) {
(name + ' is null')
}
}
}
Validation Example
As an alternative example, we might have this utility method:
{
NUMBER_PATTERN = "\\\\d+(\\\\.\\\\d+(E-?\\\\d+)?)?"
isNumber(str) {
(!str ==~ NUMBER_PATTERN) {
("Argument '$str' must be a number")
}
}
isNotZero(number) {
(number == 0) {
('Argument must not be 0')
}
}
}
http://docs.groovy-lang.org/latest/html/documentation/ 461/502
1/6/2019 Groovy Language Documentation
stringDivide( dividendStr, divisorStr) {
.isNumber(dividendStr)
.isNumber(divisorStr)
dividend = dividendStr.toDouble()
divisor = divisorStr.toDouble()
.isNotZero(divisor)
dividend / divisor
}
Example
In this example, the script sends requests to the lister object. The lister points to a UnixLister object. If it can’t handle the
request, it sends the request to the WindowsLister . If it can’t handle the request, it sends the request to the DefaultLister .
http://docs.groovy-lang.org/latest/html/documentation/ 462/502
1/6/2019 Groovy Language Documentation
{
nextInLine
( ) { nextInLine = }
listFiles(dir) {
( .getProperty('os.name') == 'Linux') {
println "ls $dir".execute().text
} {
nextInLine.listFiles(dir)
}
}
}
{
nextInLine
( ) { nextInLine = }
listFiles(dir) {
( .getProperty('os.name') == 'Windows XP') {
println "cmd.exe /c dir $dir".execute().text
} {
nextInLine.listFiles(dir)
}
}
}
{
listFiles(dir) {
(dir).eachFile { f -> println f }
}
}
lister = ( ( ()))
lister.listFiles('Downloads')
The output will be a list of les (with slightly di erent format depending on the operating system).
we could have an explicit interface, e.g. Lister , to statically type the implementations but because of duck-typing this is
optional
we could use a chain tree instead of a list, e.g. if (animal.hasBackbone()) delegate to VertebrateHandler else delegate
to InvertebrateHandler
we could decide at some point to not respond and not pass down the chain
we could use Groovy’s meta-programming capabilities to pass unknown methods down the chain
Composite Pattern
http://docs.groovy-lang.org/latest/html/documentation/ 463/502
1/6/2019 The Composite Pattern (http://en.wikipedia.org/wiki/Composite_pattern)
Groovy Language allows you to treat single instances of an object the same
Documentation
way as a group of objects. The pattern is often used with hierarchies of objects. Typically, one or more methods should be callable
in the same way for either leaf or composite nodes within the hierarchy. In such a case, composite nodes typically invoke the
same named method for each of their children nodes.
Example
Consider this usage of the composite pattern where we want to call toString() on either Leaf or Composite objects.
In Java, the Component class is essential as it provides the type used for both leaf and composite nodes. In Groovy, because of
duck-typing, we don’t need it for that purpose, however, it can still server as a useful place to place common behaviour between
the leaf and composite nodes.
http://docs.groovy-lang.org/latest/html/documentation/ 464/502
1/6/2019 Groovy Language Documentation
{
name
toString(indent) {
("-" * indent) + name
}
}
{
children = []
toString(indent) {
s = .toString(indent)
children.each { child ->
s += "\\n" + child.toString(indent + 1)
}
s
}
leftShift(component) {
children << component
}
}
{ }
root
-leaf A
-comp B
--leaf B1
--leaf B2
-leaf C
Decorator Pattern
The Decorator Pattern (http://en.wikipedia.org/wiki/Decorator_pattern) provides a mechanism to embellish the behaviour of an
object without changing its essential interface. A decorated object should be able to be substituted wherever the original (non-
decorated) object was expected. Decoration typically does not involve modifying the source code of the original object and
decorators should be able to be combined in exible ways to produce objects with several embellishments.
Traditional Example
Suppose we have the following Logger class.
{
log( message) {
println message
}
}
There might be times when it is useful to timestamp a log message, or times when we might want to change the case of the
message. We could try to build all of this functionality into our Logger class. If we did that, the Logger class would start to be
very complex. Also, everyone would obtain all of features even when they might not want a small subset of the features. Finally,
feature interaction would become quite di cult to control.
To overcome these drawbacks, we instead de ne two decorator classes. Uses of the Logger class are free to embellish their base
logger with zero or more decorator classes in whatever order they desire. The classes look like this:
http://docs.groovy-lang.org/latest/html/documentation/ 465/502
1/6/2019 Groovy Language Documentation
{
logger
(logger) {
.logger = logger
}
log( message) {
now = .instance
logger.log("$now.time: $message")
}
}
{
logger
(logger) {
.logger = logger
}
log( message) {
logger.log(message.toUpperCase())
}
}
logger = ( ( ()))
logger.log("G'day Mate")
// => Tue May 22 07:13:50 EST 2007: G'DAY MATE
You can see that we embellish the logger behaviour with both decorators. Because of the order we chose to apply the decorators,
our log message comes out capitalised and the timestamp is in normal case. If we swap the order around, let’s see what happens:
logger = ( ( ()))
logger.log('Hi There')
// => TUE MAY 22 07:13:50 EST 2007: HI THERE
( ) {
. =
}
invokeMethod( name, args) {
newargs = args.collect { arg ->
(arg ) {
arg.toLowerCase()
} {
arg
}
}
.invokeMethod(name, newargs)
}
}
It takes any class and decorates it so that any String method parameter will automatically be changed to lower case.
logger = ( ( ()))
logger.log('IMPORTANT Message')
// => Tue May 22 07:27:18 EST 2007: important message
http://docs.groovy-lang.org/latest/html/documentation/ 466/502
1/6/2019 Just be careful with ordering here. The original decoratorsGroovy
were restricted
LanguagetoDocumentation
decorating Logger objects. This decorator works
with any object type, so we can’t swap the ordering around, i.e. this won’t work:
We could overcome this limitation be generating an appropriate Proxy type at runtime but we won’t complicate the example here.
logger = ()
logger.metaClass.log = { m -> println 'message: ' + m.toUpperCase() }
logger.log('x')
// => message: X
This achieves a similar result to applying a single decorator but we have no way to easily apply and remove embellishments on the
y.
{
add(a, b) { a + b }
}
We might be interested in observing usage of the class over time. If it is buried deep within our codebase, it might be hard to
determine when it is being called and with what parameters. Also, it might be hard to know if it is performing well. We can easily
make a generic tracing decorator that prints out tracing information whenever any method on the Calc class is called and also
provide timing information about how long it took to execute. Here is the code for the tracing decorator:
( ) {
. =
}
invokeMethod( name, args) {
println "Calling $name$args"
before = .currentTimeMillis()
result = .invokeMethod(name, args)
println "Got $result in ${System.currentTimeMillis()-before} ms"
result
}
}
tracedCalc = ( ())
15 == tracedCalc.add(3, 12)
And here is what you would see after running this script:
Groovy even comes with a built-in TracingInterceptor . We can extend the built-in class like this:
{
beforeTime
beforeInvoke( , methodName, [] arguments) {
.beforeInvoke( , methodName, arguments)
beforeTime = .currentTimeMillis()
}
afterInvoke( , methodName, [] arguments, result) {
.afterInvoke( , methodName, arguments, result)
duration = .currentTimeMillis() - beforeTime
writer.write("Duration: $duration ms\\n")
writer.flush()
result
}
}
proxy = .getInstance( )
proxy.interceptor = ()
proxy. {
7 == ().add(1, 6)
}
before Calc.ctor()
after Calc.ctor()
Duration: 0 ms
before Calc.add(java.lang.Integer, java.lang.Integer)
after Calc.add(java.lang.Integer, java.lang.Integer)
Duration: 2 ms
getGroovySql() {
con = session.connection()
invoker = { , method, args ->
(method.name == "close") {
log.debug("ignoring call to Connection.close() for use by groovy.sql.Sql")
} {
log.trace("delegating $method")
con.invokeMethod(method.name, args)
}
} ;
proxy = .newProxyInstance( getClass().getClassLoader(), [ ] [],
invoker )
(proxy)
}
If there were many methods to intercept, then this approach could be modi ed to look up closure in a map by method name and
invoke it.
First de ne a class that you want to decorate (we’ll also use an interface as is normal Spring practice):
{
add(a, b)
}
{
add(a, b) { a + b }
}
id="performanceInterceptor" autowire="no"
class="org.springframework.aop.interceptor.PerformanceMonitorInterceptor"
name="loggerName" value="performance"
id="calc" class="util.CalcImpl"
class="org.springframework.aop.framework.autoproxy.BeanNameAutoProxyCreator"
name="beanNames" value="calc"
name="interceptorNames" value="performanceInterceptor"
@Grab('org.springframework:spring-context:3.2.2.RELEASE')
org.springframework.context.support.
ctx = ('beans.xml')
calc = ctx.getBean('calc')
println calc.add(3, 25)
You may have to adjust your logging.properties le for messages at log level FINEST to be displayed.
{
()
getText()
}
{
document
() { println document }
getText() { document }
}
words( text) {
text.replaceAll('[^a-zA-Z]', ' ').trim().split("\\\\s+")*.toLowerCase()
}
avgWordLength = {
words = words(it.text)
sprintf "Avg Word Length: %4.2f", words*.size().sum() / words.size()
}
modeWord = {
wordGroups = words(it.text).groupBy {it}.collectEntries { k, v -> [k, v.size()] }
maxSize = wordGroups*.value.max()
maxWords = wordGroups.findAll { it.value == maxSize }
"Mode Word(s): ${maxWords*.key.join(', ')} ($maxSize occurrences)"
}
wordCount = { d -> "Word Count: " + words(d.text).size() }
asyncDecorator( d, c) {
.INSTANCE.instantiateDelegate([ : {
withPool {
result = c.callAsync(d)
d. ()
println result. ()
}
}], [ ], d)
}
d = asyncDecorator(asyncDecorator(asyncDecorator(
(document:"This is the file with the words in it\\n\\t\\nDo you see the
words?\\n"),
// new DocumentImpl(document: new File('AsyncDecorator.groovy').text),
wordCount), modeWord), avgWordLength)
d. ()
Delegation Pattern
The Delegation Pattern (http://en.wikipedia.org/wiki/Delegation_pattern) is a technique where an object’s behavior (public
methods) is implemented by delegating responsibility to one or more associated objects.
Groovy allows the traditional style of applying the delegation pattern, e.g. see Replace Inheritance with Delegation.
http://docs.groovy-lang.org/latest/html/documentation/ 470/502
1/6/2019 Groovy Language Documentation
{
targetClass
(targetClass, ) {
.targetClass = targetClass
. =
}
( methodName) {
(methodName, methodName)
}
( methodName, asMethodName) {
targetClass.metaClass."$asMethodName" = .&"$methodName"
}
delegateAll( [] names) {
names.each { (it) }
}
delegateAll( names) {
names.each { k, v -> (k, v) }
}
delegateAll() {
. .methods*.name.each { (it) }
}
}
With this in your classpath, you can now apply the delegation pattern dynamically as shown in the following examples. First,
consider we have the following classes:
{
name
}
{
borrowAmount(amount) {
"borrow \\$$amount"
}
borrowFor(thing) {
"buy \\$thing"
}
}
lender = ()
delegator = ( , lender)
We can now use the delegator to automatically borrow methods from the lender object to extend the Person class. We can
borrow the methods as is or with a rename:
delegator. 'borrowFor'
delegator. 'borrowAmount', 'getMoney'
p = ()
The rst line above, adds the borrowFor method to the Person class by delegating to the lender object. The second line adds a
getMoney method to the Person class by delegating to the lender object’s borrowAmount method.
delegator.delegateAll()
Which will make all the methods in the delegate object available in the Person class.
{
name
@Delegate mortgageLender = ()
}
{
borrowAmount(amount) {
"borrow \\$$amount"
}
borrowFor(thing) {
"buy $thing"
}
}
p = ()
Flyweight Pattern
The Flyweight Pattern (http://en.wikipedia.org/wiki/Flyweight_pattern) is a pattern for greatly reducing memory requirements by
not requiring that heavy-weight objects be created in large numbers when dealing with systems that contain many things that are
mostly the same. If for instance, a document was modelled using a complex character class that knew about unicode, fonts,
positioning, etc., then the memory requirements could be quite large for large documents if each physical character in the
document required its own character class instance. Instead, characters themselves might be kept within Strings and we might
have one character class (or a small number such as one character class for each font type) that knew the speci cs of how to deal
with characters.
In such circumstances, we call the state that is shared with many other things (e.g. the character type) instrinsic state. It is
captured within the heavy-weight class. The state which distinguishes the physical character (maybe just its ASCII code or Unicode)
is called its extrinsic state.
Example
First we are going to model some complex aircraft (the rst being a hoax competitor of the second - not that is relevant to the
example).
{
wingspan = '80.8 m'
capacity = 1000
speed = '1046 km/h'
range = '14400 km'
// ...
}
http://docs.groovy-lang.org/latest/html/documentation/ 472/502
1/6/2019 Groovy Language Documentation
{
wingspan = '79.8 m'
capacity = 555
speed = '912 km/h'
range = '10370 km'
// ...
}
If we want to model our eet, our rst attempt might involve using many instances of these heavy-weight objects. It turns out
though that only a few small pieces of state (our extrinsic state) change for each aircraft, so we will have singletons for the heavy-
weight objects and capture the extrinsic state (bought date and asset number in the code below) separately.
{
instances = [797: (), 380: ()]
}
{
type // instrinsic state
assetNumber // extrinsic state
bought // extrinsic state
(typeCode, assetNumber, bought) {
type = .instances[typeCode]
.assetNumber = assetNumber
.bought = bought
}
describe() {
println """
Asset Number: $assetNumber
Capacity: $type.capacity people
Speed: $type.speed
Range: $type.range
Bought: $bought
"""
}
}
fleet = [
(380, 1001, '10-May-2007'),
(380, 1002, '10-Nov-2007'),
(797, 1003, '10-May-2008'),
(797, 1004, '10-Nov-2008')
]
So here, even if our eet contained hundreds of planes, we would only have one heavy-weight object for each type of aircraft.
As a further e ciency measure, we might use lazy creation of the yweight objects rather than create the initial map up front as in
the above example.
http://docs.groovy-lang.org/latest/html/documentation/ 473/502
1/6/2019 Groovy Language Documentation
Asset Number: 1001
Capacity: 555 people
Speed: 912 km/h
Range: 10370 km
Bought: 10-May-2007
Iterator Pattern
The Iterator Pattern (http://en.wikipedia.org/wiki/Iterator_pattern) allows sequential access to the elements of an aggregate object
without exposing its underlying representation.
Groovy has the iterator pattern built right in to many of its closure operators, e.g. each and eachWithIndex as well as the
for .. in loop.
For example:
printAll(container) {
(item container) { println item }
}
numbers = [ 1,2,3,4 ]
months = [ :31, :30, :31 ]
colors = [ java.awt. .BLACK, java.awt. .WHITE ]
printAll numbers
printAll months
printAll colors
1
2
3
4
May=31
Mar=31
Apr=30
java.awt.Color[r=0,g=0,b=0]
java.awt.Color[r=255,g=255,b=255]
Another example:
Results in:
http://docs.groovy-lang.org/latest/html/documentation/ 474/502
1/6/2019 Groovy Language Documentation
Position 0 contains 'java.awt.Color[r=0,g=0,b=0]'
Position 1 contains 'java.awt.Color[r=255,g=255,b=255]'
The iterator pattern is also built in to other special operators such as the eachByte , eachFile , eachDir , eachLine ,
eachObject , eachMatch operators for working with streams, URLs, les, directories and regular expressions matches.
This pattern is built in to many Groovy helper methods. You should consider using it yourself if you need to work with resources in
ways beyond what Groovy supports.
Example
Consider the following code which works with a le. First we might write some line to the le and then print its size:
f = ('junk.txt')
f.withPrintWriter { pw ->
pw.println( ())
pw.println( . .name)
}
println f.size()
// => 42
We could also read back the contents of the le a line at a time and print each line out:
Note that normal Java Reader and PrintWriter objects were used under the covers by Groovy but the code writer did not have
to worry about explicitly creating or closing those resources. The built-in Groovy methods loan the respective reader or writer to
the closure code and then tidy up after themselves. So, you are using this pattern without having to do any work.
Sometimes however, you wish to do things slightly di erently to what you can get for free using Groovy’s built-in mechanisms.
You should consider utilising this pattern within your own resource-handling operations.
Consider how you might process the list of words on each line within the le. We could actually do this one too using Groovy’s
built-in functions, but bear with us and assume we have to do some resource handling ourselves. Here is how we might write the
code without using this pattern:
reader = f.newReader()
reader.splitEachLine(' ') { wordList ->
println wordList
}
reader.close()
// =>
// [ "Mon", "Jun", "18", "22:38:17", "EST", "2007" ]
// [ "RunPattern" ]
Notice that we now have an explicit call to close() in our code. If we didn’t code it just right (here we didn’t surround the code in
a try … finally block, we run the risk of leaving the le handle open.
Let’s now apply the loan pattern. First, we’ll write a helper method:
http://docs.groovy-lang.org/latest/html/documentation/ 475/502
1/6/2019 Groovy Language Documentation
withListOfWordsForEachLine( f, c) {
r = f.newReader()
{
r.splitEachLine(' ', c)
} {
r?.close()
}
}
This is much simpler and has removed the explicit close() . This is now catered for in one spot so we can apply the appropriate
level of testing or reviewing in just one spot to be sure we have no problems.
Simple Example
Suppose we have the following system:
{
salary
}
{
name
job
}
people = [
(name: 'Tom', job: (salary: 1000)),
(name: 'Dick', job: (salary: 1200)),
]
When run, this prints out 1200 . Suppose now that we now invoke:
To overcome this problem, we can introduce a NullJob class and change the above statement to become:
{ salary = 0 }
http://docs.groovy-lang.org/latest/html/documentation/ 476/502
1/6/2019 This works as we require but it’s not always the best way to do this
Groovy with Groovy.
Language Groovy’s safe-dereference operator ( ?. )
Documentation
operator and null aware closures often allow Groovy to avoid the need to create a special null object or null class. This is
illustrated by examining a groovier way to write the above example:
Two things are going on here to allow this to work. First of all, max() is 'null aware' so that [300, null, 400].max() == 400. Secondly,
with the ?. operator, an expression like p?.job?.salary will be equal to null if salary is equal to null, or if job is equal ` null
or if p is equal to null. You don’t need to code a complex nested if ... then ... else to avoid a NullPointerException .
Tree Example
Consider the following example where we want to calculate size, cumulative sum and cumulative product of all the values in a tree
structure.
Our rst attempt has special logic within the calculation methods to handle null values.
{
left, right, value
size() {
1 + (left ? left.size() : 0) + (right ? right.size() : 0)
}
sum() {
value + (left ? left.sum() : 0) + (right ? right.sum() : 0)
}
product() {
value * (left ? left.product() : 1) * (right ? right.product() : 1)
}
}
root = (
value: 2,
left: (
value: 3,
right: (value: 4),
left: (value: 5)
)
)
println root.size()
println root.sum()
println root.product()
If we introduce the null object pattern (here by de ning the NullTree class), we can now simplify the logic in the size() , sum()
and`product()` methods. These methods now much more clearly represent the logic for the normal (and now universal) case.
Each of the methods within NullTree returns a value which represents doing nothing.
http://docs.groovy-lang.org/latest/html/documentation/ 477/502
1/6/2019 Groovy Language Documentation
{
left = (), right = (), value
size() {
1 + left.size() + right.size()
}
sum() {
value + left.sum() + right.sum()
}
product() {
value * left.product() * right.product()
}
}
{
size() { 0 }
sum() { 0 }
product() { 1 }
}
root = (
value: 2,
left: (
value: 3,
right: (value: 4),
left: (value: 5)
)
)
println root.size()
println root.sum()
println root.product()
4
14
120
Note: a slight variation with the null object pattern is to combine it with the singleton pattern. So, we wouldn’t write new NullTree()
wherever we needed a null object as shown above. Instead we would have a single null object instance which we would place
within our data structures as needed.
Example
Suppose we want to make use of the built-in Integer facilities in Groovy (which build upon the features already in Java). Those
libraries have nearly all of the features we want but not quite everything. We may not have all of the source code to the Groovy
and Java libraries so we can’t just change the library. Instead we augment the library. Groovy has a number of ways to do this. One
way is to use a Category.
http://docs.groovy-lang.org/latest/html/documentation/ 478/502
1/6/2019 Groovy Language Documentation
{
greaterThanAll( , [] others) {
greaterThanAll( , others)
}
greaterThanAll( , others) {
others.every { > it }
}
}
We have added two methods which augment the Integer methods by providing the greaterThanAll method. Categories follow
conventions where they are de ned as static methods with a special rst parameter representing the class we wish to extend. The
greaterThanAll(Integer self, others) static method becomes the greaterThanAll(other) instance method.
We de ned two versions of greaterThanAll . One which works for collections, ranges etc. The other which works with a variable
number of Integer arguments.
( ) {
4.greaterThanAll(1, 2, 3)
!5.greaterThanAll(2, 4, 6)
5.greaterThanAll(-4..4)
5.greaterThanAll([])
!5.greaterThanAll([4, 5])
}
As you can see, using this technique you can e ectively enrich an original class without having access to its source code.
Moreover, you can apply di erent enrichments in di erent parts of the system as well as work with un-enriched objects if we
need to.
Proxy Pattern
The Proxy Pattern (http://en.wikipedia.org/wiki/Proxy_pattern) allows one object to act as a pretend replacement for some other
object. In general, whoever is using the proxy, doesn’t realise that they are not using the real thing. The pattern is useful when the
real object is hard to create or use: it may exist over a network connection, or be a large object in memory, or be a le, database
or some other resource that is expensive or impossible to duplicate.
Example
One common use of the proxy pattern is when talking to remote objects in a di erent JVM. Here is the client code for creating a
proxy that talks via sockets to a server object as well as an example usage:
{
accumulate(args) {
result
s = ("localhost", 54321)
s.withObjectStreams { ois, oos ->
oos << args
result = ois.readObject()
}
s.close()
result
}
}
Here is what your server code might look like (start this rst):
http://docs.groovy-lang.org/latest/html/documentation/ 479/502
1/6/2019 Groovy Language Documentation
{
accumulate(args) {
args.inject(0) { total, arg -> total += arg }
}
}
port = 54321
accumulator = ()
server = (port)
println "Starting server on port $port"
( ) {
server.accept() { socket ->
socket.withObjectStreams { ois, oos ->
args = ois.readObject()
oos << accumulator.accumulate(args)
}
}
}
Singleton Pattern
The Singleton Pattern (http://en.wikipedia.org/wiki/Singleton_pattern) is used to make sure only one object of a particular class is
ever created. This can be useful when when exactly one object is needed to coordinate actions across a system; perhaps for
e ciency where creating lots of identical objects would be wasteful, perhaps because a particular algorithm needing a single point
of control is required or perhaps when an object is used to interact with a non-shareable resource.
It can reduce reuse. For instance, there are issues if you want to use inheritance with Singletons. If SingletonB extends
SingletonA , should there be exactly (at most) one instance of each or should the creation of an object from one of the
classes prohibit creation from the other. Also, if you decide both classes can have an instance, how do you override the
getInstance() method which is static?
It is also hard to test singletons in general because of the static methods but Groovy can support that if required.
{
votes = 0
INSTANCE = ()
getInstance() { INSTANCE }
() { }
display() { println "Collector:${hashCode()}, Votes:$votes" }
}
it has a private constructor, so no VoteCollector objects can be created in our system (except for the INSTANCE we create)
we haven’t made the updating of votes thread-safe at this point (it doesn’t add to this example)
the vote collector instance is not lazily created (if we never reference the class, the instance won’t be created; however, as soon
as we reference the class, the instance will be created even if not needed initially)
http://docs.groovy-lang.org/latest/html/documentation/ 480/502
1/6/2019 Groovy Language Documentation
collector = .instance
collector.display()
collector.votes++
collector =
.start{
collector2 = .instance
collector2.display()
collector2.votes++
collector2 =
}.join()
collector3 = .instance
collector3.display()
Here we used the instance 3 times. The second usage was even in a di erent thread (but don’t try this in a scenario with a new
class loader).
Collector:15959960, Votes:0
Collector:15959960, Votes:1
Collector:15959960, Votes:2
To support lazy-loading and multi-threading, we could just use the synchronized keyword with the getInstance() method.
This has a performance hit but will work.
We can consider variations involving double-checked locking and the volatile keyword, but see the limitations of this
approach here (http://www.ibm.com/developerworks/java/library/j-dcl/index.html).
Suppose we want to keep track of the total number of calculations that a calculator performs. One way to do that is to use a
singleton for the calculator class and keep a variable in the class with the count.
First we de ne some base classes. A Calculator class which performs calculations and records how many such calculations it
performs and a Client class which acts as a facade to the calculator.
{
total = 0
add(a, b) { total++; a + b }
getTotalCalculations() { 'Total Calculations: ' + total }
toString() { 'Calc: ' + hashCode() }
}
{
calc = ()
executeCalc(a, b) { calc.add(a, b) }
toString() { 'Client: ' + hashCode() }
}
Now we can de ne and register a MetaClass which intercepts all attempts to create a Calculator object and always provides a
pre-created instance instead. We also register this MetaClass with the Groovy system:
http://docs.groovy-lang.org/latest/html/documentation/ 481/502
1/6/2019 Groovy Language Documentation
{
INSTANCE = ()
() { ( ) }
invokeConstructor( [] arguments) { INSTANCE }
}
registry = .metaClassRegistry
registry.setMetaClass( , ())
Now we use instances of our Client class from within a script. The client class will attempt to create new instances of the
calculator but will always get the singleton.
client = ()
3 == client.executeCalc(1, 2)
println "$client, $client.calc, $client.calc.totalCalculations"
client = ()
4 == client.executeCalc(2, 2)
println "$client, $client.calc, $client.calc.totalCalculations"
Here is the result of running this script (your hashcode values may vary):
Guice Example
We can also implement the Singleton Pattern using Guice (https://github.com/google/guice).
Guice is a Java-oriented framework that supports Interface-Oriented design. Hence we create a Calculator interface rst. We
can then create our CalculatorImpl implementation and a Client object which our script will interact with. The Client class
isn’t strictly needed for this example but allows us to show that non-singleton instances are the default. Here is the code:
http://docs.groovy-lang.org/latest/html/documentation/ 482/502
1/6/2019 Groovy Language Documentation
@Grapes([@Grab('aopalliance:aopalliance:1.0'), @Grab('com.google.code.guice:guice:1.0')])
com.google.inject.*
{
add(a, b)
}
{
total = 0
add(a, b) { total++; a + b }
getTotalCalculations() { 'Total Calculations: ' + total }
toString() { 'Calc: ' + hashCode() }
}
{
@Inject calc
executeCalc(a, b) { calc.add(a, b) }
toString() { 'Client: ' + hashCode() }
}
injector = .createInjector (
[configure: { binding ->
binding.bind( )
.to( )
.asEagerSingleton() } ]
)
client = injector.getInstance( )
3 == client.executeCalc(1, 2)
println "$client, $client.calc, $client.calc.totalCalculations"
client = injector.getInstance( )
4 == client.executeCalc(2, 2)
println "$client, $client.calc, $client.calc.totalCalculations"
Note the @Inject annotation in the Client class. We can always tell right in the source code which elds will be injected.
In this example we chose to use an explicit binding. All of our dependencies (ok, only one in this example at the moment) are
con gured in the binding. The Guide injector knows about the binding and injects the dependencies as required when we create
objects. For the singleton pattern to hold, you must always use Guice to create your instances. Nothing shown so far would stop
you creating another instance of the calculator manually using new CalculatorImpl() which would of course violate the desired
singleton behaviour.
In other scenarios (though probably not in large systems), we could choose to express dependencies using annotations, such as
the following example shows:
http://docs.groovy-lang.org/latest/html/documentation/ 483/502
1/6/2019 Groovy Language Documentation
@Grapes([@Grab('aopalliance:aopalliance:1.0'), @Grab('com.google.code.guice:guice:1.0')])
com.google.inject.*
@ImplementedBy( )
{
// as before ...
}
@Singleton
{
// as before ...
}
{
// as before ...
}
injector = .createInjector()
// ...
Note the @Singleton annotation on the CalculatorImpl class and the @ImplementedBy annotation in the Calculator
interface.
When run, the above example (using either approach) yields (your hashcode values will vary):
You can see that we obtained a new client object whenever we asked for an instance but it was injected with the same calculator
object.
Spring Example
We can do the Calculator example again using Spring as follows:
http://docs.groovy-lang.org/latest/html/documentation/ 484/502
1/6/2019 Groovy Language Documentation
@Grapes([@Grab('org.springframework:spring-core:3.2.2.RELEASE'),
@Grab('org.springframework:spring-beans:3.2.2.RELEASE')])
org.springframework.beans.factory.support.*
{
add(a, b)
}
{
total = 0
add(a, b) { total++; a + b }
getTotalCalculations() { 'Total Calculations: ' + total }
toString() { 'Calc: ' + hashCode() }
}
{
( calc) { .calc = calc }
calc
executeCalc(a, b) { calc.add(a, b) }
toString() { 'Client: ' + hashCode() }
}
client = factory.getBean('client')
3 == client.executeCalc(1, 2)
println "$client, $client.calc, $client.calc.totalCalculations"
client = factory.getBean('client')
4 == client.executeCalc(2, 2)
println "$client, $client.calc, $client.calc.totalCalculations"
Further information
Simply Singleton (http://www.javaworld.com/javaworld/jw-04-2003/jw-0425-designpatterns.html?page=1)
State Pattern
The State Pattern (http://en.wikipedia.org/wiki/State_pattern) provides a structured approach to partitioning the behaviour within
complex systems. The overall behaviour of a system is partitioned into well-de ned states. Typically, each state is implemented by
a class. The overall system behaviour can be determined rstly by knowing the current state of the system; secondly, by
understanding the behaviour possible while in that state (as embodied in the methods of the class corresponding to that state).
Example
Here is an example:
http://docs.groovy-lang.org/latest/html/documentation/ 485/502
1/6/2019 Groovy Language Documentation
{
context = ()
connect() {
context.state.connect()
}
disconnect() {
context.state.disconnect()
}
send_message(message) {
context.state.send_message(message)
}
receive_message() {
context.state.receive_message()
}
}
{
state = ( )
}
{
context
(context) {
.context = context
inform()
}
}
{
(context) {
(context)
}
inform() {
println "offline"
}
connect() {
context.state = (context)
}
disconnect() {
println "error: not connected"
}
send_message(message) {
println "error: not connected"
}
receive_message() {
println "error: not connected"
}
}
{
(context) {
(context)
}
inform() {
println "connected"
}
connect() {
println "error: already connected"
}
disconnect() {
context.state = (context)
}
send_message(message) {
println "\"$message\" sent"
}
receive_message() {
println "message received"
http://docs.groovy-lang.org/latest/html/documentation/ 486/502
1/6/2019 } Groovy Language Documentation
}
client = ()
client.send_message("Hello")
client.connect()
client.send_message("Hello")
client.connect()
client.receive_message()
client.disconnect()
offline
error: not connected
connected
"Hello" sent
error: already connected
message received
offline
One of the great things about a dynamic language like Groovy though is that we can take this example and express it in many
di erent ways depending on our particular needs. Some potential variations for this example are shown below.
{
connect()
disconnect()
send_message(message)
receive_message()
}
Then our Client , Online and 'O ine` classes could be modi ed to implement that interface, e.g.:
{
// ... as before ...
}
{
// ... as before ...
}
{
// ... as before ...
}
You might ask: Haven’t we just introduced additional boilerplate code? Can’t we rely on duck-typing for this? The answer is 'yes'
and 'no'. We can get away with duck-typing but one of the key intentions of the state pattern is to partition complexity. If we know
that the client class and each state class all satisfy one interface, then we have placed some key boundaries around the
complexity. We can look at any state class in isolation and know the bounds of behaviour possible for that state.
We don’t have to use interfaces for this, but it helps express the intent of this particular style of partitioning and it helps reduce
the size of our unit tests (we would have to have additional tests in place to express this intent in languages which have less
support for interface-oriented design).
http://docs.groovy-lang.org/latest/html/documentation/ 487/502
1/6/2019 Groovy Language Documentation
{
registry = .metaClassRegistry
create(objectClass, param) {
registry.getMetaClass(objectClass).invokeConstructor([param] [])
}
}
{
context
setContext(context) {
.context = context
}
invokeMethod( name, arg) {
context.invokeMethod(name, arg)
}
startFrom(initialState) {
setContext( .create(initialState, ))
}
}
{
client
transitionTo(nextState) {
client.setContext( .create(nextState, client))
}
}
This is all quite generic and can be used wherever we want to introduce the state pattern. Here is what our code would look like
now:
http://docs.groovy-lang.org/latest/html/documentation/ 488/502
1/6/2019 Groovy Language Documentation
{
() {
startFrom( )
}
}
{
(client) {
(client)
println "offline"
}
connect() {
transitionTo( )
}
disconnect() {
println "error: not connected"
}
send_message(message) {
println "error: not connected"
}
receive_message() {
println "error: not connected"
}
}
{
(client) {
(client)
println "connected"
}
connect() {
println "error: already connected"
}
disconnect() {
transitionTo( )
}
send_message(message) {
println "\"$message\" sent"
}
receive_message() {
println "message received"
}
}
client = ()
client.send_message("Hello")
client.connect()
client.send_message("Hello")
client.connect()
client.receive_message()
client.disconnect()
You can see here the startFrom and transitionTo methods begin to give our example code a DSL feel.
We can de ne the following generic helper functions ( rst discussed here (http://www.bytemycode.com/snippets/snippet/640/)):
http://docs.groovy-lang.org/latest/html/documentation/ 489/502
1/6/2019 Groovy Language Documentation
{
fsm
fromState
toState
(a_fsm) {
fsm = a_fsm
}
on(a_event) {
= a_event
on(a_event, a_transitioner) {
on(a_event)
a_transitioner. =
a_transitioner.call()
(a_fromState) {
fromState = a_fromState
to(a_toState) {
a_toState, "Invalid toState: $a_toState"
toState = a_toState
fsm.registerTransition( )
isValid() {
&& fromState && toState
}
toString() {
"$event: $fromState=>$toState"
}
}
http://docs.groovy-lang.org/latest/html/documentation/ 490/502
1/6/2019 Groovy Language Documentation
{
transitions = [:]
initialState
currentState
(a_initialState) {
a_initialState, "You need to provide an initial state"
initialState = a_initialState
currentState = a_initialState
}
record() {
.newInstance( )
}
reset() {
currentState = initialState
}
isState(a_state) {
currentState == a_state
}
registerTransition(a_grammar) {
a_grammar.isValid(), "Invalid transition ($a_grammar)"
transition
= a_grammar.
fromState = a_grammar.fromState
toState = a_grammar.toState
(!transitions[ ]) {
transitions[ ] = [:]
}
transition = transitions[ ]
!transition[fromState], "Duplicate fromState $fromState for transition $a_grammar"
transition[fromState] = toState
}
fire(a_event) {
currentState, "Invalid current state '$currentState': passed into constructor"
transitions.containsKey(a_event), "Invalid event '$a_event', should be one of
${transitions.keySet()}"
transition = transitions[a_event]
nextState = transition[currentState]
nextState, "There is no transition from '$currentState' to any other state"
currentState = nextState
currentState
}
}
http://docs.groovy-lang.org/latest/html/documentation/ 491/502
1/6/2019 Groovy Language Documentation
{
fsm
setUp() {
fsm = .newInstance('offline')
recorder = fsm.record()
recorder.on('connect'). ('offline').to('online')
recorder.on('disconnect'). ('online').to('offline')
recorder.on('send_message'). ('online').to('online')
recorder.on('receive_message'). ('online').to('online')
}
testInitialState() {
fsm.isState('offline')
}
testOfflineState() {
shouldFail{
fsm.fire('send_message')
}
shouldFail{
fsm.fire('receive_message')
}
shouldFail{
fsm.fire('disconnect')
}
'online' == fsm.fire('connect')
}
testOnlineState() {
fsm.fire('connect')
fsm.fire('send_message')
fsm.fire('receive_message')
shouldFail{
fsm.fire('connect')
}
'offline' == fsm.fire('disconnect')
}
}
This example isn’t an exact equivalent of the others. It doesn’t use prede ned Online and Offline classes. Instead it de nes
the entire state machine on the y as needed. See the previous reference (http://www.bytemycode.com/snippets/snippet/640/)
for more elaborate examples of this style.
Strategy Pattern
The Strategy Pattern (http://en.wikipedia.org/wiki/Strategy_pattern) allows you to abstract away particular algorithms from their
usage. This allows you to easily swap the algorithm being used without having to change the calling code. The general form of the
pattern is:
In Groovy, because of its ability to treat code as a rst class object using anonymous methods (which we loosely call Closures), the
need for the strategy pattern is greatly reduced. You can simply place algorithms inside Closures.
http://docs.groovy-lang.org/latest/html/documentation/ 492/502
1/6/2019 Example Groovy Language Documentation
First let’s look at the traditional way of encapsulating the Strategy Pattern.
{
execute(n, m)
}
{
execute(n, m) { n * m }
}
{
execute(n, m) {
result = 0
n.times{
result += m
}
result
}
}
sampleData = [
[3, 4, 12],
[5, -5, -25]
]
[] multiplicationStrategies = [
(),
()
]
Here we have de ned an interface Calc which our concrete strategy classes will implement (we could also have used an abstract
class). We then de ned two algorithms for doing simple multiplication: CalcByMult the normal way, and CalcByManyAdds using
only addition (don’t try this one using negative numbers - yes we could x this but it would just make the example longer). We
then use normal polymorphism (http://en.wikipedia.org/wiki/Polymorphism_in_object-oriented_programming) to invoke the
algorithms.
Here is the Groovier way to achieve the same thing using Closures:
multiplicationStrategies = [
{ n, m -> n * m },
{ n, m -> result = 0; n.times{ result += m }; result }
]
sampleData = [
[3, 4, 12],
[5, -5, -25]
]
http://docs.groovy-lang.org/latest/html/documentation/ 493/502
1/6/2019 The Template Method Pattern (http://en.wikipedia.org/wiki/Template_method_pattern) abstracts away the details of several
Groovy Language Documentation
algorithms. The generic part of an algorithm is contained within a base class. Particular implementation details are captured
within base classes. The generic pattern of classes involved looks like this:
Example
In this example, Accumulator captures the essence of the accumulation algorithm. The base classes Sum and Product provide
particular customised ways to use the generic accumulation algorithm.
{
initial
doAccumulate(total, v)
accumulate(values) {
total = initial
values.each { v -> total = doAccumulate(total, v) }
total
}
}
{
() { initial = 0 }
doAccumulate(total, v) { total + v }
}
{
() { initial = 1 }
doAccumulate(total, v) { total * v }
}
println ().accumulate([1,2,3,4])
println ().accumulate([1,2,3,4])
10
24
In this particular case, you could use Groovy’s inject method to achieve a similar result using Closures:
Thanks to duck-typing, this would also work with other objects which support an add (plus() in Groovy) method, e.g.:
In this particular case, you could use Groovy’s inject method to achieve a similar result using Closures:
Using closures this way looks more like the Strategy Pattern but if we realise that the built-in inject method is the generic part of
the algorithm for our template method, then the Closures become the customised parts of the template method pattern.
Visitor Pattern
The Visitor Pattern (http://en.wikipedia.org/wiki/Visitor_pattern) is one of those well-known but not often used patterns. I think
this is strange, as it is really a nice thing.
The goal of the pattern is to separate an algorithm from an object structure. A practical result of this separation is the ability to
add new operations to existing object structures without modifying those structures.
Simple Example
This example considers how to calculate the bounds of shapes (or collections of shapes). Our rst attempt uses the traditional
visitor pattern. We will see a more Groovy way to do this shortly.
http://docs.groovy-lang.org/latest/html/documentation/ 495/502
1/6/2019 Groovy Language Documentation
{ }
{
x, y, width, height
(rect) {
(!rect)
minx = [rect.x, x].min()
maxx = [rect.x + width, x + width].max()
miny = [rect.y, y].min()
maxy = [rect.y + height, y + height].max()
(minx, miny, maxx - minx, maxy - miny)
}
accept(visitor) {
visitor.visit_rectangle( )
}
}
{
x1, y1, x2, y2
accept(visitor){
visitor.visit_line( )
}
}
{
shapes = []
add(shape) { shapes += shape }
remove(shape) { shapes -= shape }
accept(visitor) {
visitor.visit_group( )
}
}
{
bounds
visit_rectangle(rectangle) {
(bounds)
bounds = bounds. (rectangle)
bounds = rectangle
}
visit_line(line) {
line_bounds = (line.x1, line.y1, line.x2-line.y1, line.x2-line.y2)
(bounds)
bounds = bounds. (line_bounds)
bounds = line_bounds
}
visit_group( ) {
.shapes.each { shape -> shape.accept( ) }
}
}
http://docs.groovy-lang.org/latest/html/documentation/ 496/502
1/6/2019 = () Groovy Language Documentation
.add( (100, 40, 10, 5))
.add( (100, 70, 10, 5))
.add( (90, 30, 60, 5))
visitor = ()
.accept(visitor)
bounding_box = visitor.bounds
println bounding_box. ()
We can improve the clarity of our code (and make it about half the size) by making use of Groovy Closures as follows:
{
accept( ) { ( ) }
}
{
x, y, w, h
bounds() { }
(rect) {
(!rect)
minx = [ rect.x, x ].min()
maxx = [ rect.x + w, x + w ].max()
miny = [ rect.y, y ].min()
maxy = [ rect.y + h, y + h ].max()
(x:minx, y:miny, w:maxx - minx, h:maxy - miny)
}
}
{
x1, y1, x2, y2
bounds() {
(x:[x1, x2].min(), y:[y1, y2].min(), w:(x2 - x1).abs(), h:(y2 - y1).abs())
}
}
{
shapes = []
leftShift(shape) { shapes += shape }
accept( ) { shapes.each{it.accept( )} }
}
= ()
<< (x:100, y:40, w:10, h:5)
<< (x:100, y:70, w:10, h:5)
<< (x1:90, y1:30, x2:60, y2:5)
bounds
.accept{ bounds = it.bounds(). (bounds) }
println bounds. ()
Advanced Example
http://docs.groovy-lang.org/latest/html/documentation/ 497/502
1/6/2019 Groovy Language Documentation
{
visit( n1)
visit( n2)
}
{
accept( visitor)
}
{
[] children = [0]
accept( visitor) {
visitor.visit( )
( i = 0; i < children.length; ++i) {
children[i].accept(visitor)
}
}
}
{
[] children = [0]
accept( visitor) {
visitor.visit( )
( i = 0; i < children.length; ++i) {
children[i].accept(visitor)
}
}
}
{
count = 0
visit( n1) {
count++
}
visit( n2){}
}
root = ()
root.children = [2]
root.children[0] = ()
root.children[1] = ()
Then we have one NodeType1 object as root and one of the children is also a NodeType1 instance. The other child is a
NodeType2 instance. That means using NodeType1Counter here should count 2 NodeType1 objects.
http://docs.groovy-lang.org/latest/html/documentation/ 498/502
1/6/2019 Groovy Language Documentation
{
visit( n1)
visit( n2)
}
{
visit( n1) {
( i = 0; i < n1.children.length; ++i) {
n1.children[i].accept( )
}
}
visit( n2) {
( i = 0; i < n2.children.length; ++i) {
n2.children[i].accept( )
}
}
}
{
accept( visitor)
}
{
[] children = [0]
accept( visitor) {
visitor.visit( )
}
}
{
[] children = [0];
accept( visitor) {
visitor.visit( )
}
}
{
count = 0
visit( n1) {
count++
.visit(n1)
}
}
Some small changes but with big e ect… the visitor is now recursive and tells me how to iterate. The implementation in the Nodes
is minimized to visitor.visit(this) , DefaultVisitor is now able to catch the new types, we can stop iteration by not
delegating to super. Of course the big disadvantage now is that it is no longer iterative, but you can’t get all the bene ts.
Make it Groovy
The question now is how to make that a bit more Groovy. Didn’t you nd this visitor.visit(this) strange? Why is it there?
The answer is to simulate double dispatch. In Java the compile time type is used, so when I visitor.visit(children[i]) then
the compiler won’t be able to nd the correct method, because Visitor does not contain a method visit(Visitable) . And
even if it would, we would like to visit the more special methods with NodeType1 or NodeType2 .
Now Groovy is not using the static type, Groovy uses the runtime type. This means I could do visitor.visit(children[i])
directly. Hmm.. since we minimized the accept method to just do the double dispatch part and since the runtime type system of
Groovy will already cover that.. do we need the accept method? I think you can guess that I would answer no. But we can do more.
We had the disadvantage of not knowing how to handle unknown tree elements. We had to extends the interface Visitor for
that, resulting in changes to DefaultVisitor and then we have the task to provide a useful default like iterating the node or not
doing anything at all. Now with Groovy we can catch that case by adding a visit(Visitable) method that does nothing. That
would be the same in Java btw.
But don’t let us stop here… do we need the Visitor interface? If we don’t have the accept method, then we don’t need the
Visitor interface at all. So the new code would be:
http://docs.groovy-lang.org/latest/html/documentation/ 499/502
1/6/2019 Groovy Language Documentation
{
visit( n1) {
n1.children.each { visit(it) }
}
visit( n2) {
n2.children.each { visit(it) }
}
visit( v) { }
}
{ }
{
[] children = []
}
{
[] children = []
}
{
count = 0
visit( n1) {
count++
.visit(n1)
}
}
Looks like we saved a few lines of code here. But we made more. The Visitable nodes now do not refer to any Visitor class
or interface. For me this is the best level of separation you could get here. But do we really need to stop here? No. Let us change
the Visitable interface a little and let it return the children we want to visit next. This allows us a general iteration method.
{
visit( v) {
doIteraton(v)
}
doIteraton( v) {
v.children.each {
visit(it)
}
}
}
{
[] getChildren()
}
{
[] children = []
}
{
[] children = []
}
{
count = 0
visit( n1) {
count++
.visit(n1)
}
}
http://docs.groovy-lang.org/latest/html/documentation/ 500/502
1/6/2019 DefaultVisitor now looks a bit di erent. I added a doIteration method
Groovy Language that will get the children it should iterate over and
Documentation
then call visit on each element. Per default this will call visit(Visitable) which then iterates over the children of this child. I
changed Visitable to ensure that any node will be able to return children (even if empty). I didn’t have to change the
NodeType1 and NodeType2 class, because the way the children led was de ned already made them a property, which means
Groovy is so nice to generate a get method for us. No the really interesting part is NodeType1Counter , it is interesting because
we have not changed it. super.visit(n1) will now call visit(Visitable) which will call doIteration which will start the
next level of iteration. So no change. But visit(it) will call visit(NodeType1) if it is of type NodeType1 . In fact we don’t need
the doIteration method, we could do that in visit(Visitable) too, but I thought this variant is better, because it allows us to
write a new Visitor that overwrites visit( Visitable ) for error cases which of course means we must not do super.visit(n1)
but doIteration(n1) .
Summary
In the end we got ~40% less code, a robust and stable architecture and we completely removed the Visitor from the Visitable. I
heard about visitor implementations based on Re ection to get a more generic version. Well, with this you see there is really no
need to do such thing. If we add new types we don’t need to change anything. It is said that the visitor pattern doesn’t t extreme
programming techniques very well because you need to make changes to so many classes all the time. I think I proved that this is
because of Java not because the pattern is bad or something.
There are variants of the Visitor pattern, like the acyclic visitor pattern, that tries to solve the problem of adding new node types
with special visitors. I don’t like that very much, it works with casts, catches the ClassCastException and other nasty things. In
the end it tries to solve something we don’t even get with the Groovy version.
One more thing. NodeType1Counter could be implemented in Java as well. Groovy will recognize the visit methods and call them
as needed because DefaultVisitor is still Groovy and does all the magic.
Further Information
Componentization: the Visitor example (http://se.ethz.ch/~meyer/publications/computer/visitor.pdf)
3.19.2. References
1. Erich Gamma, Richard Helm, Ralph Johnson, John Vlissides (1995). Design Patterns: Elements of Reusable Object-Oriented
Software. Addison-Wesley. ISBN 0-201-63361-2.
2. Martin Fowler (1999). Refactoring: Improving the Design of Existing Code. Addison-Wesley. ISBN 0-201-48567-2.
4. Eric Freeman, Elisabeth Freeman, Kathy Sierra, Bert Bates (2004). Head First Design Patterns. O’Reilly. ISBN 0-596-00712-4. *A
great book to read, informative as well as amusing.
5. Dierk Koenig with Andrew Glover, Paul King, Guillaume Laforge and Jon Skeet (2007). Groovy in Action. Manning. ISBN 1-
932394-84-2.
6. Brad Appleton (1999). Pizza Inversion - a Pattern for E cient Resource Consumption (http://www.bradapp.com/docs/pizza-
inv.html).
7. Design Patterns in Dynamic Languages by Neil Ford. Houston Java User’s Group. Examples in Groovy and Ruby.
http://www.oracle.com/technetwork/server-storage/ts-4961-159222.pdf (http://www.oracle.com/technetwork/server-
storage/ts-4961-159222.pdf)
4. Acknowledgements
4.1. Contributors
The Groovy team would like to thank the contributors of this documentation (by alphabetical order):
J Brown (https://github.com/JBrownVisualSpection)
4.2. License
This work is licensed under the Apache License, Version 2.0 (http://www.apache.org/licenses/LICENSE-2.0).
Version 2.5.5
Last updated 2018-12-21 09:39:08 AEST
http://docs.groovy-lang.org/latest/html/documentation/ 502/502