Java Reference
In-Depth Information
Figure 4.2. Groovy adds a map-based constructor to Java classes, regardless of what constructors are already
included.
though the Java version already specifies two constructors and neither is the one I want.
The following Groovy script creates some
Person
instances using three different mech-
anisms, none of which appear in the Java class:
1
The term
map-based
refers to the fact that the attributes are set using the key-value notation used in Groovy maps.
The constructor doesn't actually use a map to do its job.
def
buffy =
new
Person(name:'Buffy')
assert
buffy.id == 0
assert
buffy.name == 'Buffy'
def
faith =
new
Person(name:'Faith',id:1)
assert
faith.id == 1
assert
faith.name == 'Faith'
def
willow = [name:'Willow',id:2]
as
Person
assert
willow.getId() == 2
assert
willow.getName() == 'Willow'
The instances
buffy
and
faith
are created using the map-based constructor, first setting
only the
name
, and then setting both the
name
and the
id
. I'm then able to verify, us-
ing Groovy's built-in
assert
method (omitting its optional parentheses), that the person's
properties are set correctly.
Incidentally, all the
assert
statements that seem to be accessing private properties of the
class directly really aren't. Groovy goes through the getter and setter methods provided in
the Java class when it looks like properties are being accessed or assigned. I can prove this
by modifying the implementation of the getter method to return more than just the name: