【发布时间】:2018-02-16 12:30:50
【问题描述】:
我基本上希望有一个enum 与特定的方法,例如
public interface PropertyTypeMethods {
public int getTypeId();
public void setTypeId(Integer typeId);
}
类似的东西
public enum BasePropertyTypes implements PropertyTypeMethods {
ONE, TWO;
private int typeId;
@Override
public int getTypeId() {
return typeId;
}
@Override
public void setTypeId(Integer typeId) {
this.typeId = typeId;
}
}
以及此枚举的扩展版本,例如
public enum ExtendedPropertyTypes implements PropertyTypeMethods {
HUNDRED, THOUSEND;
// same as above
}
这将导致ONE.setTypeId(1) ==> ONE.getTypeId()==1 //true。这是基本概念。但现在我想调用一个通用方法,例如
private <E extends Enum<E> & PropertyTypeMethods> void initEnum(Enum<E> curType) {
// the below approach does not work :-/
curType.setTypeId(1); // or any other reasonable value....
但不知何故,我无法弄清楚 正确 方法签名是什么。在question 之后,我发现至少有一部分是谜题——
但仍然没有得到它的方法签名。仍然不清楚如何在签名中正确指定curType 以执行适当的调用。
【问题讨论】:
-
为什么是
<E extends Enum<E> & PropertyTypeMethodes>?要设置类型,<E extends PropertyTypeMethods>就足够了。 -
枚举应该是常量。如果您想要一个可变的“枚举”,请将其设为普通的旧类。
-
只需创建一个类,给它一个
private或protected构造函数并添加常量实例。瞧,它基本上是一个可变和可扩展的枚举。您还可以添加一个static方法来提供该类的所有可用实例,例如枚举上的values()。 -
就像安迪说的,枚举值应该是常量。我认为您真正想要的是EnumMap。
-
好吧,我需要查看其他建议...。关于为什么? 主要问题是这个枚举已经在代码中杂乱无章。现在有一个突破性的变化来手动设置 id - 而不是硬编码(因为它是)。因此,请求......我很想拥有不同的 - 从一开始就