我基本上想要一个具有特定方法的枚举
,例如
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 来执行适当的调用。
最佳答案
这会起作用:
private <E extends Enum<E> & PropertyTypeMethods> void initEnum(E curType) {
curType.setTypeId(1);
}
但是,我认为创建可变的 Enum
不是一个好主意(它们是常量值上的标签,而不是携带状态的单例)。此外,您应该编写需要 Enum
参数的方法,因为它们只需要关心其接口(interface):
// This will be easier to work with down the road
private void initEnum(PropertyTypeMethods curType) {
curType.setTypeId(1);
}
关于Java 泛型类型用于枚举实现上的方法签名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48826848/