O'Reilly logo

Programming Groovy 2 by Venkat Subramaniam

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required