我正在尝试为一组枚举类编写一些Java代码.
每个枚举都封装了一些概念上不同的数据,因此将它们组合起来没有意义.枚举也映射到数据库中的值,因此还共享一些与从数据库加载数据相关的常见操作,包括实例操作和静态操作.
我需要概括我所拥有的枚举类的集合,这样我就可以将这些枚举中的任何一个传递到另一个类中,该类执行和缓存与每个不同枚举相关的数据库查找.
由于缓存/查找类还将依赖于每个枚举中定义的公共和静态方法,我如何编写解决方案以便保证可以传递给类的任何枚举都具有所需的方法?
通常的方法是定义接口,但接口不允许使用静态方法.
或者,您可以使用抽象类来定义接口和一些常见的实现,但我不相信枚举是可能的(我知道枚举必须扩展Enum类并且不能扩展).
我有什么选择让我能够确保我的所有枚举实现我需要的方法?
枚举示例:
public enum MyEnum{
VALUE_ONE("my data");
VALUE_TWO("some other data");
/**
* Used when mapping enums to database values - if that sounds odd,
* it is: it's legacy stuff
*
* set via private constructor
*/
private String myValue;
//private constructor not shown
public static MyEnum lookupEnumByString(String enumValue){
//find the enum that corresponds to the supplied string
}
public String getValue(){
return myValue;
}
}
Run Code Online (Sandbox Code Playgroud)
这一切都很复杂,可能会有错误,但我希望你能得到这个想法.
// I'm not sure about the right type arguments here
public interface MyEnumInterface<E extends MyEnumInterface & Enum<E>> {
public static boolean aUsefulNonStaticMethod();
String getValue();
MyEnumInfo<E> enumInfo();
}
/** contains some helper methods */
public class MyEnumInfo<E extends MyEnumInterface<E>> {
private static <E extends MyEnumInterface<E>> MyEnumInfo(Class<E> enumClass) {...}
// static factory method
public static <E extends MyEnumInterface<E>> MyEnumInfo<E> infoForClass(Class<E> enumClass) {
... return a cached value
}
public static <E extends MyEnumInterface<E>> MyEnumInfo(E e) {
return infoForClass(e.getClass());
}
// some helper methods replacing static methods of the enum class
E enumForValue(String value) {....}
}
public enum MyEnum implements MyEnumInterface<MyEnum> {
VALUE_ONE("my data");
VALUE_TWO("some other data");
private String myValue; //set via private constructor
//private constructor not shown
public boolean aUsefulNonStaticMethod(){
//do something useful
}
public String getValue(){
return myValue;
}
// the ONLY static method in each class
public static MyEnumInfo<E> staticEnumInfo() {
return MyEnumInfo.infoForClass(MyEnumClass.class);
}
// the non-static version of the above (may be useful or not)
public MyEnumInfo<E> enumInfo() {
return MyEnumInfo.infoForClass(getClass());
}
}
Run Code Online (Sandbox Code Playgroud)
这有点奇怪,除了Enum.name()之外你还在使用另一个String,你需要它吗?
由于所有枚举扩展了Enum,你不能让他们共享任何代码.您可以做的最好的事情是将它全部委托给实用程序类中的辅助静态方法.
没有办法强制类实现静态方法,这是可以理解的,因为没有办法(除了反射)来调用它们.