我想使用Groovy2.1.9在几个不同的枚举之间共享类似的功能。枚举都用于生成XML,因此我为它们提供了一个名为xmlRepresentation
的属性。以下是其中的两个枚举:
enum Location {
CollegeCampus('College Campus'), HighSchool('High School'), Online('Online')
Location(String xmlRep) {
this.xmlRepresentation = xmlRep
}
String toString() {
xmlRepresentation
}
String xmlRepresentation
}
enum InstructorType {
CollegeFaculty('College Faculty'), HighSchoolFaculty('High School Faculty')
InstructorType(String xmlRep) {
this.xmlRepresentation = xmlRep
}
String toString() {
xmlRepresentation
}
String xmlRepresentation
}
如您所见,我必须在这两个枚举中声明xmlRepresentation
属性、toString
方法和构造函数。我想分享这些属性/方法,但我不认为我可以继承枚举。我试过用一种混音器却没有任何结果:
class XmlRepresentable {
String xmlRepresentation
XmlRepresentable(String xmlRepresentation) {
this.xmlRepresentation = xmlRepresentation
}
String toString() {
this.xmlRepresentation
}
}
@Mixin(XmlRepresentable)
enum Location {
CollegeCampus('College Campus'), HighSchool('High School'), Online('Online')
}
这就产生了错误Could not find matching constructor for: com.company.DeliveryFormat
。
有谁知道我如何共享这个功能并保持代码干燥吗?谢谢!
发布于 2014-07-24 23:05:00
下面是迁移到Groovy2.3.0及更高版本的一些动机。( :)使用DRYness的trait
数量
trait Base {
final String xmlRepresentation
void setup(String xmlRep) {
this.xmlRepresentation = xmlRep
}
String toString() {
xmlRepresentation
}
String getValue() {
xmlRepresentation
}
}
enum Location implements Base {
CollegeCampus('College Campus'), HighSchool('High School'), Online('Online')
Location(String xmlRep) { setup xmlRep }
}
enum InstructorType implements Base {
CollegeFaculty('College Faculty'), HighSchoolFaculty('High School Faculty')
InstructorType(String xmlRep) { setup xmlRep }
}
assert Location.HighSchool in Location
assert Location.Online.value == 'Online'
assert InstructorType.CollegeFaculty in InstructorType
我认为你现在拥有的AFAIK没有什么可以做的。
https://stackoverflow.com/questions/24936797
复制相似问题