如何启用枚举继承 [英] How to enable enum inheritance
问题描述
我正在编写一个库,它有一组预定义的枚举值。
假设,我的枚举如下所示。
I'm writing a library, which has a predefined set of values for an enum. Let say, my enum looks as below.
public enum EnumClass {
FIRST("first"),
SECOND("second"),
THIRD("third");
private String httpMethodType;
}
现在使用此库的客户可能需要添加更多值。假设客户端需要添加 CUSTOM_FIRST
和 CUSTOM_SECOND
。这不会覆盖任何现有值,但会使枚举有5个值。
Now the client, who is using this library may need to add few more values. Let say, the client needs to add CUSTOM_FIRST
and CUSTOM_SECOND
. This is not overwriting any existing values, but makes the enum having 5 values.
在此之后,我应该可以使用类似< ?扩展EnumClass>
以获得5种不变的可能性。
After this, I should be able to use something like <? extends EnumClass>
to have 5 constant possibilities.
实现这一目标的最佳方法是什么?
What would be the best approach to achieve this?
推荐答案
你不能有 enum
扩展另一个 enum
,并且您不能通过继承将值添加到现有的枚举
。
You cannot have an enum
extend another enum
, and you cannot "add" values to an existing enum
through inheritance.
但是, enum
s可以实现 interface
s。
However, enum
s can implement interface
s.
我要做的是让原来的 enum
实现一个标记界面
(即没有方法声明),那么你的客户可以创建自己的枚举
实现相同的接口
。
What I would do is have the original enum
implement a marker interface
(i.e. no method declarations), then your client could create their own enum
implementing the same interface
.
然后你的 enum
值会被他们共同的界面引用
。
Then your enum
values would be referred to by their common interface
.
为了加强要求,你可以让你的界面声明相关的方法,例如:在你的情况下,行中的某些东西是get String getHTTPMethodType();
。
In order to strenghten the requirements, you could have your interface declare relevant methods, e.g. in your case, something in the lines of public String getHTTPMethodType();
.
这将迫使实现 enum
s为该方法提供实现。
That would force implementing enum
s to provide an implementation for that method.
此设置加上适当的API文档应有助于以相对受控的方式添加功能。
This setting coupled with adequate API documentation should help adding functionality in a relatively controlled way.
自包含示例(不介意这里的懒名称)
Self-contained example (don't mind the lazy names here)
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
这篇关于如何启用枚举继承的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!