我想使用Groovy 2.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
}
Run Code Online (Sandbox Code Playgroud)
如您所见,我必须在这两个枚举中声明xmlRepresentation属性,toString方法和构造函数.我想分享这些属性/方法,但我认为我不能继承枚举.我试过没有任何运气使用mixin:
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')
}
Run Code Online (Sandbox Code Playgroud)
这产生了错误Could not find matching constructor for: com.company.DeliveryFormat.
有谁知道我如何分享这个功能并保持我的代码干?谢谢!
这是移动到Groovy 2.3.0及更高版本的一点动机.:)使用一些DRYnesstrait
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
Run Code Online (Sandbox Code Playgroud)
对于你现在拥有的AFAIK,我认为没有什么可以做的.
| 归档时间: |
|
| 查看次数: |
316 次 |
| 最近记录: |