Java Reference
In-Depth Information
Listing 4.5. GroundHog Day—an example of Date and Calendar in the Groovy JDK
I get an instance of the Calendar class by accessing its instance property. Of course,
there's no instance property in Calendar , but the syntax actually means that I invoke the
static getInstance method with no arguments. Then I call set with the appropriate ar-
guments for Groundhog Day and the first day of spring. Extracting a Date instance from
the Calendar is done through the getTime method (sigh [ 6 ] ), which again is invoked by
accessing the time property. So far this is straight Java, except that I'm invoking methods
via properties and omitting optional parentheses.
6 Seriously, couldn't the method getDate have been used to extract a Date from a Calendar ?
I can subtract dates, though, because the Groovy JDK shows that the minus method in
Date returns the number of days between them. The Date class has a next method and
a previous method and implements compareTo . Those are the requirements necessary
for a class to be used as part of a range, so I can check the math by invoking the size
method on a range. The size of a range counts both ends, so I have to correct for the poten-
tial off-by-one error by subtracting one.
The bottom line is that there are six weeks and four days between Groundhog Day and the
first day of spring (March 20). In other words, if the groundhog sees his shadow the result-
ing six more weeks of winter is actually a (slightly) early spring anyway. [ 7 ]
7 Yes, that's a long way to go for a gag, but it does clearly show a mix of Java and Groovy that takes advantage of
both Groovy JDK methods and operator overloading. The joke is just a side benefit.
One last convenience should be noted here. In Java, arrays have a length property,
strings have a length method, collections have a size method, NodeList s have a
 
 
Search WWH ::




Custom Search