ExpandoMetaClass and categories
The meta class of a class decides what a call means. Groovy lets a program replace part of it at run time, which adds a method to a class the program does not own, and a category does the same inside a block instead of everywhere.
A method on Integer
expando.groovy
Integer.metaClass.double = { -> delegate * 2 }
println 21.double()
println 5.double()
println Integer.metaClass.respondsTo(7, 'double').size()
groovy expando.groovy
42
10
1
delegate inside the closure is the receiver of the call, so 21.double() passes 21. The change lasts for the whole JVM process: every Integer in this program now has the method, and a library that runs later sees it too.
A category and use
category.groovy
class TextCategory {
static String shouted(String self) {
self.toUpperCase() + '!'
}
}
use(TextCategory) {
println 'hello'.shouted()
}
println 'hello'.metaClass.respondsTo('shouted').empty
groovy category.groovy
HELLO!
true
A category is a class of static methods whose first parameter is the receiver. use applies it to the block and removes it afterwards, which the last line proves. That scope is the reason a library prefers a category to a change of the global meta class.
@Category
categorized.groovy
import groovy.lang.Category
@Category(String)
class TextCategory {
String shouted() {
toUpperCase() + '!'
}
String quiet() {
toLowerCase()
}
}
use(TextCategory) {
println 'hello'.shouted()
println 'HELLO'.quiet()
}
groovy categorized.groovy
HELLO!
hello
@Category(String) writes the static methods and the receiver parameter from the instance methods, which is shorter and keeps an editor's type information. It is the same category as the block above.
Related
- methodMissing and propertyMissing: the other hook of the meta class.
- AST transformations in use: the methods a compiler writes instead.
Автор статьи: Arthur Isaev