Java extendable enumeration

空扰寡人 提交于 2020-01-01 09:23:18

问题


Is there a way to write an enumeration that can be extended. I have several methods that I would like to always have available for my enumerations. For example I use an enumeration for my database fields. I include the actual field name in the database.

public enum ORDERFIELDS
        {
            OrderID("Order_ID");
            private String FieldName;

            private ORDERFIELDS(String fname)
                {
                    this.FieldName = fname;
                }

            public String getFieldName()
                {
                    return FieldName;
                }
        } 

回答1:


If I understand correctly, what you'd like to do is something like this:

public abstract class DatabaseField {
    private String fieldName;

    private DatabaseField(String fieldName) {
        this.fieldName = fieldName;
    }

    public String getFieldName() {
        return fieldName;
    }
}

Then define your enum to extend this class. However, unfortunately an enum cannot extend a class, but it can implement an interface, so the best you can do at the moment is define an interface which includes the getFieldName() method and have all your enums implement this interface.

However, this means that you'll have to duplicate the implementation of this method (and any others) in all your enums. There are some suggestions in this question about ways to minimise this duplication.




回答2:


All enums implicitly extend java.lang.Enum. Since Java does not support multiple inheritance, an enum cannot extend anything else.




回答3:


Enums can implement interfaces but not extend since when compiled they translate to a java.lang.Enum.




回答4:


Abstract enums are potentially very useful (and currently not allowed). But a proposal and prototype exists if you'd like to lobby someone in Sun to add it:

http://freddy33.blogspot.com/2007/11/abstract-enum-ricky-carlson-way.html

Sun RFE:

http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6570766




回答5:


For a throwback to the pre-Java 5 days, take a look at Item 21, Chapter 5,Effective Java by Josh Bloch. He talks about extending "enums" by adding values, but perhaps you could use some of the techniques to add a new method?




回答6:


Hand craft the enum in a mechanism similar to that defined in Josh Bloch's Effective Java.

I would add that if you need to "extend" the enum, then perhaps an enum isn't the construct you are after. They are meant to be static constants IMHO.



来源:https://stackoverflow.com/questions/221892/java-extendable-enumeration

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!