Java Reference
In-Depth Information
ServletCategory
Whether you use
ServletCategory
or not, its combination of metaprogramming and
operator overloading make it an excellent example of how Groovy helps Java.
Categories in Groovy 2.0
Groovy2.0introduced an alternative syntax fordefining categories. Inthe
ServletCat-
egory
discussed in this section, the category class contains static methods whose first ar-
gument is the class being modified. In the new notation you can use annotations and in-
stance methods instead.
As an example, consider formatting numbers as currency. The
j
ava.text.NumberFormat
class has a method called
getCurrencyInstance
,
which has both a no-arg method that formats for the current locale and an overloaded ver-
sion that takes a
java.util.Locale
argument. The classic way to add an
asCur-
rency
method to
Number
that employs the currency formatter is
import java.text.NumberFormat
class CurrencyCategory {
static String asCurrency(Number amount) {
NumberFormat.currencyInstance.format(amount)
}
static String asCurrency(Number amount, Locale loc) {
NumberFormat.getCurrencyInstance(loc).format(amount)
}
}
use(CurrencyCategory) {
def amount = 1234567.89012
println amount.asCurrency()
println amount.asCurrency(Locale.GERMANY)
println amount.asCurrency(new Locale('hin','IN'))
}
The new way to implement a category uses the
@Category
annotation, which takes the
class to be modified as an argument. Then instance methods are used inside the category,