Chapter 9. Metaprogramming and DSLs in Groovy

In this chapter, we will cover:

  • Querying methods and properties
  • Dynamically extending classes with new methods
  • Overriding methods dynamically
  • Adding performance logging to methods
  • Adding a caching functionality around methods
  • Adding transparent imports to a script
  • DSL for executing commands over SSH
  • DSL for generating reports from logfiles

Introduction

The recipes presented in this chapter will cover a number of advanced metaprogramming concepts in Groovy in detail. Metaprogramming is the characteristic of a programming language to modify the aspect of a class at runtime or compile time, that is, adding and intercepting methods, implementing new interfaces, and so on.

Groovy, thanks to its dynamic nature, makes metaprogramming extremely easy. This capability is considered by many to be one of the most helpful features of the language.

Taking an advantage of Groovy's metaprogramming capabilities bring great new possibilities that would be very difficult or just plain impossible to write with Java alone. The first recipes of this chapter cover several interesting solutions such as dynamically adding methods to classes, intercepting methods, and exploring Abstract Syntax Tree (AST) capabilities.

Metaprogramming is especially important for the creation of DSLs (Domain Specific Language), small domain-specific languages dedicated to a particular domain problem. In this chapter, we will also dedicate two recipes to different aspects of how to write a DSL with Groovy.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.146.34.146