Java可扩展枚举 [英] Java extendable enumeration
问题描述
公开枚举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屋!