在Groovy 1.6中引入了使用categories/mixins的简单机制。以前,类别类的方法必须声明为静态的,并且第一个参数指示它们可以应用于哪类对象(如上面的类Foo
)。
我觉得这有点尴尬,因为一旦类别的方法“混入”目标类,它们是非静态的,但在类别类中它们是静态的。
无论如何,因为Groovy 1.6中,你可以做到这一点,而不是
// Define the category
class MyCategory {
void doIt() {
println "done"
}
void doIt2() {
println "done2"
}
}
// Mix the category into the target class
@Mixin (MyCategory)
class MyClass {
void callMixin() {
doIt()
}
}
// Test that it works
def obj = new MyClass()
obj.callMixin()
一些其他的功能都可用。如果您想要限制该类别可应用的类别,请使用@Category
注释。例如,如果你只是想申请MyCategory
到MyClass
(或它的子类),其定义为:
@Category(MyClass)
class MyCategory {
// Implementation omitted
}
而不是使用@Mixin
(如上)在编译时在混合类的,你可以将它们混合在运行时,而不是使用:
MyClass.mixin MyCategory
在你使用Grails,Bootstrap.groovy
在这里你可以这样做的地方。