Java可扩展枚举 [英] Java extendable enumeration

查看:166
本文介绍了Java可扩展枚举的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法编写可以扩展的枚举。我有几种方法,我总是有可用于我的枚举。例如我使用枚举我的数据库字段。我在数据库中包含实际的字段名称。

 公开枚举ORDERFIELDS 
{
OrderID(Order_ID);
private String FieldName;

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

public String getFieldName()
{
return FieldName;
}
}


解决方案

我理解正确,你想做的是这样的:

  public abstract class DatabaseField {
private字符串fieldName;

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

public String getFieldName(){
return fieldName;
}
}

然后定义你的枚举来扩展这个类。然而,不幸的是,枚举不能扩展一个类,但它可以实现一个接口,所以目前最好的做法是定义一个包含getFieldName()方法并且所有枚举实现这个接口的接口。



但是,这意味着您必须在所有枚举中复制此方法(以及任何其他方法)的实现。 此问题中有一些关于如何尽量减少这种重复的建议。


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;
                }
        } 

解决方案

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.

这篇关于Java可扩展枚举的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆