Java Reference
In-Depth Information
Listing 4.7. Testing the
ImmutablePoint
class
In the test the
ImmutablePoint
class is instantiated by specifying the values of
x
and
y
as constructor arguments. This is necessary, because there are no set methods available.
I can access the properties through the regular dynamically generated get methods, but if I
try to modify a property the attempt will throw a
ReadOnlyPropertyException
.
The @
Immutable
annotation is very powerful, but it has limitations. You can only apply
it to classes that contain primitives or certain library classes, like
String
or
Date
. It also
works on classes that contain properties that are also immutable. For example, here's an
ImmutableLine
, which contains two
ImmutablePoint
instances:
@Immutable
class ImmutableLine {
ImmutablePoint start
ImmutablePoint end
def getLength() {
double dx = end.x - start.x
double dy = end.y - start.y
return Math.sqrt(dx*dx + dy*dy)
}
String toString() { "from $start to $end" }
}