Java Reference
In-Depth Information
getLength method, and so on. In Groovy you can invoke size on all of them to get the
proper behavior. In this case the Groovy JDK has been used to correct a historical incon-
sistency in Java.
TheGroovyJDKisfullofhelpfulmethods.Evenifyourapplicationisplanningtouseonly
Java library classes I encourage you to check the Groovy JDK for possible simplifications
and enhancements.
I mentioned runtime metaprogramming, which is done through the metaclass. One of
the more interesting features of Groovy, though, is compile-time metaprogramming done
through AST transformations, which is the subject of the next section.
4.4. Cool AST transformations
Groovy 1.6 introduced Abstract Syntax Tree (AST) transformations. The idea is to place
annotations on Groovy classes and invoke the compiler, which builds a syntax tree as usual
and then modifies it in interesting ways. Writing AST transformations is done through vari-
ous builder classes, but that's not my primary concern here. Instead I want to show some of
the AST transformations that Groovy provides in the standard library and demonstrate that
they can be applied to Java classes, too.
4.4.1. Delegating to contained objects
Let's start with delegation. Current design principles tend to favor delegation over inher-
itance, viewing inheritance as too highly coupled. Instead of extending a class in order to
support all its methods, with delegation you wrap an instance of one class inside anoth-
er. You then implement all the same methods in the outer class that the contained class
provides, delegating each call to the corresponding method on the contained object. In this
way your class has the same interface as the contained object but is not otherwise related
to it.
Writing all those “pass-through” methods can be a pain, though. Groovy introduced the
@Delegate annotation to take care of all that work for you.
Search WWH ::




Custom Search