2011-08-29 29 views
2

我有一個mixin類,它爲不共享共同遺產的不同類型的功能捆綁在一起。混合是使用@Mixin註釋應用的,因此它在編譯時處理。Groovy中'return this'的類型@Mixin

作爲方法調用的結果,一些mixin方法返回這個。問題是這個是混合類型,而不是基類的類型。當我想要在應用程序的其餘部分中鍵入工作時拋出一個ClassCastException異常,說混合類型不能轉換爲基類型。

在下面的示例代碼中,return this返回類型爲AMixin的對象而不是類型爲BaseClass的對象。

我該如何讓return this返回一個BaseClass類型的對象而不是AMixin類型的對象?

class AMixin { 

    def getWhatIWant(){ 
    if(isWhatIwant){ 
     return this 
    } else { 
     getChildWhatIWant() 
    } 
    } 

    def getChildWhatIWant(){ 
    for (def child in childred) { 
     def whatIWant = child.getWhatIWant() 
     if (whatIWant) { 
      return whatIWant 
     } 
    } 
    return null 
    } 
} 


@Mixin(AMixin) 
class BaseClass { 
    boolean isWhatiWant 
    List<baseClass> children 
} 

回答

3

我只是碰到了這個同樣的情況。我通過在具體類中將'this'設置爲具體類中的私有變量'me'並在Mixin類中返回'我'來解決此問題。例如:

class MyMixin { 
    def mixinMethod() { 
     // do stuff 
     return me 
    } 
} 

@Mixin(MyMixin) 
class MyConcreteClass { 
    private MyConcreteClass me 
    MyConcreteClass() { 
     me = this 
    } 
} 

我覺得它有點笨拙,但我認爲這比其他解決方案簡單得多。我個人需要能夠在多個類中使用相同的Mixin,並且聽起來像這種其他提議的解決方案不會允許這樣做,如果您不能將多個類別分配給單個Mixin類。

+0

此解決方案有效,謝謝。由於我的Mixin必須被初始化,所以我選擇用這個方法調用這個方法init(this),所以我可以通過這種方式將「真實的」這個傳遞給Mixin - 對我來說似乎更加清潔。但是,兩種解決方法都有不對的地方,它們不應該是必需的。 – Ice09

+0

這種方法解決了我的問題,但是Ice09已經說過這種解決方法並不合適。 – Ruben

2

我創建的類加鹼類別的AMixin類和BaseClass的從底部延伸.....(http://groovy.codehaus.org/Category+and+Mixin+transformations

在groovyConsole中執行該我得到

BaseClass的@ 39c931fb

class Base { 
    boolean isWhatIwant 
    List<BaseClass> children 
} 

@Category(Base) 
class AMixin { 

    def getWhatIWant(){ 
    if(isWhatIwant){ 
     return this 
    } else { 
     getChildWhatIWant() 
    } 
    } 

    def getChildWhatIWant(){ 
    for (def child in children) { 
     def whatIWant = child.getWhatIWant() 
     if (whatIWant) { 
      return whatIWant 
     } 
    } 
    return null 
    } 
} 


@Mixin(AMixin) 
public class BaseClass extends Base { 

} 

def b = new BaseClass(isWhatIwant:true) 
println b.getWhatIWant() 

編輯只是一個DummyClass。我知道這是很尷尬的,它的作品....我敢肯定Guillaume Laforge可以回答它是如何工作...

class DummyClass { 

} 

@Category(DummyClass) 
class AMixin { 

    def getWhatIWant(){ 
    if(isWhatIwant){ 
     return this 
    } else { 
     getChildWhatIWant() 
    } 
    } 

    def getChildWhatIWant(){ 
    for (def child in children) { 
     def whatIWant = child.getWhatIWant() 
     if (whatIWant) { 
      return whatIWant 
     } 
    } 
    return null 
    } 
} 


@Mixin(AMixin) 
public class BaseClass extends DummyClass { 
    boolean isWhatIwant 
    List<BaseClass> children 
} 

def b = new BaseClass(isWhatIwant:true) 
println b.getWhatIWant() 
+0

Mixin類上的@Category(Base)註釋有什麼影響?我認爲這是不可能的,如果我有多個基類,例如BaseA,BaseB和BaseC。 – Ruben

+0

不,你不能在Mixin中有多個類別的基類,但是你可以有多個具有相同類別的mixin,這有助於形成一種「多層次」。 @Category在groovy中用於元編程和擴展類。 – jjchiw

+0

但是我爲什麼要將BaseClass的AMixin類擴展爲Category?我只需要在BaseClass中提供AMixin功能。 – Ruben