13.1 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 ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access