3. Using the MetaClass
in Groovy
String.metaClass.getRandomChar = {
def chars = delegate.chars
chars[new Random().nextInt(chars.size())]
}
quot;abcdquot;.randomChar
4. Categories
• Another method of metaprogramming
• Good for functionality that:
• spans classes
• should be reverted after execution
5. Category Example:
RandomCategory
• Add rand() method to Integer
• Add rand() method to List
• Add rand(count) method to List
6. Mixins
• Permanent, application-wide class changes
• Amplifications or utilities added to classes
• Simpler to use than categories (no ‘use’ block is
necessary)
• Can be mixed into classes or objects
7. Mixin Example:
String Utilities Mixin
•Add isAlpha() to String
• Add isAlphaNumeric() to String
8. Advanced Mixin Example:
Groovy Measures
9.meters + 34.centimeters
9.034
• Uses JScience for unit conversion
• Test -- Source
• by Jeff Brown
9. methodMissing
Dynamic Finders in Grails
class GORM {
def dynamicMethods = [...] // an array of dynamic methods that use regex
def methodMissing(String name, args) {
def method = dynamicMethods.find { it.match(name) }
if(method) {
GORM.metaClass.quot;$namequot; = { Object[] varArgs ->
method.invoke(delegate, name, varArgs)
}
return method.invoke(delegate,name, args)
}
else throw new MissingMethodException(name, delegate, args)
}
}