我正在使用Grails创建发票管理应用程序,并且遇到继承问题。
如果我的意图是每个发票应包含行/项目的集合,并且将发票格式化以进行打印时,则按日期对项目进行排序,并按类别分为列表,然后在不同的方式下计算每行的价格每种具体类型的方式(计时项目将在rates属性中按小时查找,定价项目在创建时会分配一个价格)。
节点发票具有属性“items”,它是Item对象的集合。
我的域类的来源:
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
}
有问题的代码的来源:
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:无此类属性:类的类别:TimedItem
Stacktrace指示以上示例的第六行。
最佳答案
您使用的枚举错误。 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")
}
}
关于oop - 从抽象类继承属性,并对抽象属性进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2229552/