Groovy MetaClass - 将类别方法添加到适当的metaClasses

时间:2010-03-05 14:35:26

标签: grails groovy categories metaclass mixins

我在Grails插件中使用了几个类别。如,

class Foo {
    static foo(ClassA a,Object someArg) { ... }
    static bar(ClassB b,Object... someArgs) { ... }
}

我正在寻找将这些方法添加到元类的最佳方法,这样我就不必使用类别类,只需将它们作为实例方法调用即可。如,

aInstance.foo(someArg)

bInstance.bar(someArgs)

是否有一个Groovy / Grails类或方法可以帮助我做到这一点,或者我是否在迭代这些方法并自己添加它们?

1 个答案:

答案 0 :(得分:4)

在Groovy 1.6中,引入了一种更简单的使用类别/混合的机制。以前,类别类的方法必须声明为static,第一个参数指示它们可以应用于哪个对象类(如上面的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是您可以执行此操作的地方。

相关问题