1

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

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

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

aInstance.foo(someArg)

bInstance.bar(someArgs)

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

4

1 回答 1

4

在 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注解。例如,如果您只想应用于MyCategoryMyClass或其子类),请将其定义为:

@Category(MyClass)
class MyCategory {
  // Implementation omitted
}

除了在编译时使用@Mixin(如上所述)混合类别,您可以在运行时将它们混合,而不是使用:

MyClass.mixin MyCategory

在您使用 Grails 时,Bootstrap.groovy您可能会这样做。

于 2010-03-05T15:25:13.697 回答