Power Groovy DSL Features
[ 182 ]
then:
cust.idForFirstName() == "fred"
cust.idForSurname() == "flintstone"
cust.idForStreet() == "rock_road"
Adding overloaded methods
Whenever we add a method to the ExpandoMetaClass that has the same signature
as an existing method, the original method is overridden. In the following snippet,
we can see that it is the last String blanked method that is in place after we override on
subsequent occasions:
given:
String.metaClass.blanks { delegate.replaceAll(/./) {'%'}}
String.metaClass.blanks { delegate.replaceAll(/./) {'@'}}
String.metaClass.blanks { delegate.replaceAll(/./) {'*'}}
expect:
"A String".blanks() == "********"
To add overloaded versions of methods, we can continue to add new methods.
As long as the signatures are different from the last each method, it will be
added as an overloaded method:
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"
http://www.ebook3000.com