在 Groovy 1.6 中,引入了一种更简单的使用类别/mixin 的机制。以前类别类的方法必须声明为静态,第一个参数指示它们可以应用于哪个对象类(如您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
您可能会这样做。