2010-02-09 64 views
0

我正在使用Grails創建發票管理應用程序,並且遇到繼承問題。從抽象類繼承屬性,並在抽象屬性上對集合進行排序

如果我的意圖是,每張發票都應該包含一行/項目集合,並且發票格式化爲打印時,項目按日期排序,按類別分成列表,然後確定每行的價格以不同的方式爲每個具體類型計算(定時項目將在費率屬性中查找每小時,在創建時,定價項目會被分配一個價格)。

節點發票有一個屬性「items」,它是Item對象的集合。

來源我的領域類:

invoiceInstance.items.add(new TimedItem(description:"waffle", minutes:60, date:new Date(),category:"OTHER")) 
def firstList = [] 
def lastList = [] 
invoiceInstance.items.sort{it.date} 
invoiceInstance.items.each(){ 
    switch(((Item)it).category){ 
     case "LETTER": 
      firstList.add(it) 
     break; 
     default: 
      lastList.add(it) 
    } 
} 

錯誤消息:
groovy.lang.MissingPropertyException:

class Invoice { 
    static constraints = { 
    }   
    String client 

    Date dateCreated 
    Date lastUpdated 
    CostProfile rates 

    def relatesToMany = [items : Item] 
    Set items = new HashSet() 
} 

abstract class Item{ 
    static constraints = { 
    } 
    String description 
    Date date 
    enum category {SERVICE,GOODS,OTHER} 
    def belongsTo = Invoice 
    Invoice invoice 
} 

class TimedItem extends Item{ 

    static constraints = { 
    } 

    int minutes 
} 

class PricedItem extends Item{ 

    static constraints = { 
    } 

    BigDecimal cost 
    BigDecimal taxrate 
} 

問題代碼的來源沒有這樣的屬性:類別類: TimedItem

Stacktrace指示第6行上面的例子。

+0

是否有原因轉換爲物品?這對我來說似乎沒有必要。 – Snake 2010-02-09 14:03:46

回答

1

您使用的是枚舉錯誤。 enum關鍵字與class關鍵字類似。所以當你定義你的枚舉類型時,你從來沒有給過類的實例。雖然您可以將枚舉的定義保留在抽象Item類中,但爲了清晰起見,我將它移出了外部。

class Invoice { 
    Set items = new HashSet() 
} 

enum ItemCategory {SERVICE,GOODS,OTHER} 

abstract class Item{ 
    String description 
    ItemCategory category 
} 

class TimedItem extends Item{ 
    int minutes 
} 


def invoice = new Invoice() 
invoice.items.add(new TimedItem(description:"waffle", minutes:60, category: ItemCategory.OTHER)) 

invoice.items.each(){ 
    switch(it.category){ 
     case ItemCategory.OTHER: 
      println("Other found") 
     break 
     default: 
      println("Default") 
    } 
} 
+0

我把枚舉定義在grails-app/domain/ItemCategory.groovy中 在線: invoice.items.add(new TimedItem(description:「waffle」,minutes:60,category:ItemCategory.OTHER)) 我得到這個: groovy.lang.MissingPropertyException:沒有這樣的屬性:類的ItemCategory:InvoiceController 我需要某種導入語句來訪問ItemCategory的魔術值嗎? – Emyr 2010-02-10 10:30:32

+0

我相信這是正確的。 import a.package.ItemCategory – Blacktiger 2010-02-10 16:29:10

+0

好的,我還沒有在這個應用程序中聲明任何包,我需要添加一個只是爲了這個枚舉? – Emyr 2010-02-11 09:58:20