首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >创造干泡

创造干泡
EN

Stack Overflow用户
提问于 2014-07-24 14:40:46
回答 1查看 376关注 0票数 2

我想使用Groovy2.1.9在几个不同的枚举之间共享类似的功能。枚举都用于生成XML,因此我为它们提供了一个名为xmlRepresentation的属性。以下是其中的两个枚举:

代码语言:javascript
运行
复制
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方法和构造函数。我想分享这些属性/方法,但我不认为我可以继承枚举。我试过用一种混音器却没有任何结果:

代码语言:javascript
运行
复制
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

有谁知道我如何共享这个功能并保持代码干燥吗?谢谢!

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2014-07-24 23:05:00

下面是迁移到Groovy2.3.0及更高版本的一些动机。( :)使用DRYness的trait数量

代码语言:javascript
运行
复制
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没有什么可以做的。

票数 5
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/24936797

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档