Chapter 7
[ 183 ]
When we are overloading subsequent methods with different signatures, we can
make use of the append operator <<:
given:
String.metaClass.static.valueAndType << { double d ->
"${d.class.name}:${valueOf(d)}"
}
String.metaClass.static.valueAndType << { float f ->
"${f.class.name}:${valueOf(f)}"
}
String.metaClass.static.valueAndType << { int i ->
"${i.class.name}:${valueOf(i)}"
}
String.metaClass.static.valueAndType << { long l ->
"${l.class.name}:${valueOf(l)}"
}
expect:
String.valueAndType(1.0) == "java.lang.Double:1.0"
String.valueAndType(3.333f) == "java.lang.Float:3.333"
String.valueAndType(101) == "java.lang.Integer:101"
String.valueAndType(1000000L) == "java.lang.Long:1000000"
Adding constructors
Constructors can be added to a class by using the constructor property of metaclass.
Just be wary when doing this so as not to call the default constructor. The mechanism
used by metaclass to call the constructor will cause a stack overflow, if you do:
given:
Customer.metaClass.constructor = {
String first, String last -> new Customer(
firstName:first,
surname:last)
}
when:
def c = new Customer("Fred", "Flintstone" )
then:
c.firstName == "Fred"
c.surname == "Flintstone"