Book Image

Groovy 2 Cookbook

Book Image

Groovy 2 Cookbook

Overview of this book

Get up to speed with Groovy, a language for the Java Virtual Machine (JVM) that integrates features of both object-oriented and functional programming. This book will show you the powerful features of Groovy 2 applied to real-world scenarios and how the dynamic nature of the language makes it very simple to tackle problems that would otherwise require hours or days of research and implementation. Groovy 2 Cookbook contains a vast number of recipes covering many facets of today's programming landscape. From language-specific topics such as closures and metaprogramming, to more advanced applications of Groovy flexibility such as DSL and testing techniques, this book gives you quick solutions to everyday problems. The recipes in this book start from the basics of installing Groovy and running your first scripts and continue with progressively more advanced examples that will help you to take advantage of the language's amazing features. Packed with hundreds of tried-and-true Groovy recipes, Groovy 2 Cookbook includes code segments covering many specialized APIs to work with files and collections, manipulate XML, work with REST services and JSON, create asynchronous tasks, and more. But Groovy does more than just ease traditional Java development: it brings modern programming features to the Java platform like closures, duck-typing, and metaprogramming. In this new book, you'll find code examples that you can use in your projects right away along with a discussion about how and why the solution works. Focusing on what's useful and tricky, Groovy 2 Cookbook offers a wealth of useful code for all Java and Groovy programmers, not just advanced practitioners.
Table of Contents (17 chapters)
Groovy 2 Cookbook
Credits
About the Authors
About the Reviewers
www.PacktPub.com
Preface
Index

Dynamically extending classes with new methods


One of the exciting characteristics of Groovy is Meta Object Protocol (MOP). In a nutshell, the term metaprogramming refers to writing code that can dynamically change its behavior at runtime. A Meta Object Protocol refers to the capabilities of a dynamic language that enable metaprogramming. In this recipe, we are going to look at one of the capabilities of the MOP, which is ExpandoMetaClass.

Groovy's ExpandoMetaClass lets you assign behavior and state to classes at runtime without editing the original source code; it is essentially a layer above the original class. In the next section of the recipe, we will show you how to achieve such a result.

How to do it...

Adding a new method to a Groovy (or Java) class is straightforward. We are going to perform the following given steps to add a getInEuros method to the BigDecimal Java class in order to convert US dollars to euros:

  1. In a new Groovy script, type the following code:

    import java.text.NumberFormat...