我基本上想要具有特定方法的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....
但是,我无法弄清楚正确的方法签名是什么。在此问题之后,我发现了难题的至少部分 - 但是仍然没有为方法签名而得到它。仍然不清楚如何在签名中正确指定curType
来执行适当的呼叫。
这将有效:
private <E extends Enum<E> & PropertyTypeMethods> void initEnum(E curType) {
curType.setTypeId(1);
}
但是,我认为制作可变的 Enum
s不是一个好主意(它们本来是在恒定价值观上是标签,而不是携带国家的单例(。此外,您应该不需要Enum
参数的方法,而他们应关心的是其接口:
// This will be easier to work with down the road
private void initEnum(PropertyTypeMethods curType) {
curType.setTypeId(1);
}
正确的签名将只是
private void initEnum(PropertyTypeMethods onject) {
object.setTypeId(1);
}
但正如安迪·特纳(Andy Turner(所提到的,预计枚举是不变的,即只有最终的不可变地。因此,枚举也具有构造函数枚举类型。
如果您的枚举更复杂,则是实现它们如下的常见方法
public enum BasePropertyTypes implements PropertyTypeMethods {
ONE (new PropertyTypeMethods() {
@Override
public int getTypeId() {
return 1;
}
});
private final PropertyTypeMethods m;
BasePropertyTypes(PropertyTypeMethods m) {
this.m = m;
}
@Override
public int getTypeId()
{
return this.m.getTypeId();
}
}
但是,从您的示例中,我建议您查看您的实际问题。建议枚举根本不是正确的方式。