[英]Java generic Enum
对于我在Swing中的图标我有不同的枚举,如:
public enum Icon32 {
STOP("resources/icons/x32/stop.ico"),
RUN("resources/icons/x32/run.ico");
private File path;
private Icon32(String path) {
this.path = new File(path);
}
public File getFile() {
return path;
}
要么
public enum Tab {
XML("resources/icons/x32/tab/tab_1.ico"), QR("resources/icons/x32/tab/tab_2.ico"),ABOUT("resources/icons/x32/tab/tab_3.ico");
private File path;
private Tab(String path) {
this.path = new File(path);
}
public File getFile() {
return path;
}
}
我创建了一个抽象实现:
public abstract class AbstractImageType {
private File path;
private AbstractImageType(String path) {
this.path = new File(path);
}
public File getFile() {
return path;
}
@Override
public String toString() {
return path.toString();
}
}
但Enum无法扩展:
Syntax error on token "extends", implements expected
现在我的问题是,是否可以创建一个通用类“AbstractImageType”来实现方法和构造函数? 所以我只想插入枚举值?
像这样的东西:
public enum Icon32 extends AbstractImageType {
STOP("resources/icons/x32/stop.ico"),
RUN("resources/icons/x32/run.ico");
}
java中的枚举不支持类的继承,因为每个enum
实际上都是一个扩展Enum
的简单类。 由于不支持多重继承,因此无法为2个枚举创建基类。
您可以为此目的停止使用枚举,即切换到常规类或使用委托创建File,即接受枚举成员并返回File
实例的实用程序。
您可以将AbstractImageType
作为一个接口,让您的枚举实现该接口。
public interface AbstractImageType {
File getFile();
}
public enum Icon32 implements AbstractImageType {
STOP("resources/icons/x32/stop.ico"),
RUN("resources/icons/x32/run.ico");
private File path;
private Icon32(String path) {
this.path = new File(path);
}
public File getFile() {
return path;
}
}
不幸的是,它不可能对枚举使用任何类型的继承,因为它会破坏Liskov替换原则 。 Java 8将在接口中具有方法的默认实现 ,但它们可能不会扩展到构造函数。
您可以做的最好的事情就是生成代码,例如在eclipse中使用自定义模板 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.