Groovy is a great language to write DSL implementations. The Groovy syntax allows for example to leave out parenthesis or semi colons, which results in better readable DSL (which is actually Groovy code).
One Simple Example
To run a DSL script we can use the GroovyShell class and evaluate the script. By default the script is evaluated with an instance of groovy.lang.Script class. But we can extends this Script class and write our DSL allowed methods, which can then be used by the DSL script. We pass our own Script class to the GroovyShellwith an CompilerConfiguration object. The CompilerConfiguration allows us to set a new base script class to be used.
- groovy.lang.Script class
- GroovyShell class
- CompilerConfiguration class
The following sample is a simple DSL to change the state of a Car object. Notice we implicitly access the Car object that is passed to the GroovyShell via abinding. The custom CarScript class can access the car object via the binding and change it's state:
* Groovy Doc - ExpandoMetaClass - Domain-Specific Language (2)