2010-03-05 43 views
1

我在我的Grails插件中使用了几个类别。例如,Groovy MetaClass - 将类别方法添加到适当的元类

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

我在寻找添加这些方法来元类,这样我就不必使用分类等级,并且可以只调用它们作为实例方法的最佳途径。例如,

aInstance.foo(someArg) 

bInstance.bar(someArgs) 

是否有一个Groovy/Grails的类或方法,将帮助我做到这一点还是我卡住通过迭代的方法和添加他们自己来讲吗?

回答

4

在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注释。例如,如果你只是想申请MyCategoryMyClass(或它的子类),其定义为:

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

而不是使用@Mixin(如上)在编译时在混合类的,你可以将它们混合在运行时,而不是使用:

MyClass.mixin MyCategory 

在你使用Grails,Bootstrap.groovy在这里你可以这样做的地方。