您不能让enum
扩展另一个enum
,并且您不能通过继承将值“添加”到现有的enum
。
但是,enum
s可以实施interface
s。
我会做的是有原来的enum
实现一个标记interface
(即没有方法声明),然后客户可以创建自己的enum
实现相同interface
。
然后你的enum
值将被它们共同的interface
引用。
为了加强要求,你可以让你的接口声明相关的方法,例如在你的情况,在public String getHTTPMethodType();
行的东西。
这将强制执行enum
s为该方法提供实现。
此设置加上适当的API文档应该有助于以相对受控的方式添加功能。
自足例如(不介意这里的慵懒名)
package test;
import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String[] args) {
List<HTTPMethodConvertible> blah = new ArrayList<>();
blah.add(LibraryEnum.FIRST);
blah.add(ClientEnum.BLABLABLA);
for (HTTPMethodConvertible element: blah) {
System.out.println(element.getHTTPMethodType());
}
}
static interface HTTPMethodConvertible {
public String getHTTPMethodType();
}
static enum LibraryEnum implements HTTPMethodConvertible {
FIRST("first"),
SECOND("second"),
THIRD("third");
String httpMethodType;
LibraryEnum(String s) {
httpMethodType = s;
}
public String getHTTPMethodType() {
return httpMethodType;
}
}
static enum ClientEnum implements HTTPMethodConvertible {
FOO("GET"),BAR("PUT"),BLAH("OPTIONS"),MEH("DELETE"),BLABLABLA("POST");
String httpMethodType;
ClientEnum(String s){
httpMethodType = s;
}
public String getHTTPMethodType() {
return httpMethodType;
}
}
}
输出
first
POST
这将有利于http://stackoverflow.com/a/478431/3138755 – Rahul
当你明确知道可能的已知值的数量时,枚举是很好的。如果你期望它被扩展,你可能永远都不应该使用枚举,并且检查你当前枚举的设计目标,并且可能会放弃实现精心设计的界面的类。 –