Java Reference
In-Depth Information
The
@Grab
annotation downloads both the given library and its dependencies. The syntax
uses Maven structure, using colons to connect the group ID, the artifact ID, and the version
number. Alternatively, you can specify the sections individually:
@Grab(group='org.apache.commons', module='commons-math3', version='3.0')
The behavior is equivalent in either case.
There isn't much more to Grapes than this. In order to show an interesting example that re-
quires an external Java library, let me present a simple case of Groovy metaprogramming.
There's nothing about it that requires Grapes in particular, but it shows how a small amount
of metaprogramming can make a Java library class groovier. Using Grapes in the script al-
lows me to send it to a client without compiling it or providing the library dependencies.
The Grape annotations will handle the rest.
The
Complex
class represents a complex number, which combines real and imaginary
parts. The class contains a two-argument constructor, as shown, that takes the real and ima-
ginary parts as parameters. Many methods are defined on the class, so that it generalizes
basic numerical computations to the complex domain.
Recall that in Groovy every operator delegates to a method call. Interestingly enough, the
Complex
class already has a method called
multiply
for computing the product of two
complex numbers. Because the
*
operator in Groovy uses the
multiply
method, that op-
erator can be used immediately:
assert
first.multiply(second) == first * second
Again, this is a Java class. Fortunately, the developers of the class chose to include a meth-
od called
multiply
, so Groovy can use the
*
operator with complex numbers.
What about all the other mathematical operations? Most don't line up as cleanly. For ex-
ample, the class uses
add
instead of
plus
and
subtract
instead of
minus
. It's easy
to connect them, however, by adding the appropriate methods to the metaclass associated
with
Complex
when viewed through Groovy.
As a reminder, every class accessed through Groovy contains a metaclass, and the meta-
class is an
Expando
. This means that methods and properties can be added to the meta-