Injecting Methods Using Categories

Groovy categories provide a controlled way to inject methods—the effect of method injection is contained within a block of code. A category is an object that has the ability to alter a class’s MetaClass. It does so within the scope of the block and the executing thread. It reverses the change when we exit the block. Categories can be nested, and we can also apply multiple categories in a single block. We will explore the behavior and use of categories using examples in this section.

Suppose we have a Social Security number in a String or StringBuilder. We want to inject a method toSSN that will return the string in the format xxx-xx-xxxx. Let’s discuss some ways to achieve this.

Say the first plan of attack ...

Get Programming Groovy 2 now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.