2010-03-05 82 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在這裏你可以這樣做的地方。