考虑以下枚举:
public enum AllColors {
WHITE,
RED,
GRAY,
GREEN,
BLUE,
BLACK
}
public enum GrayscaleColors {
WHITE,
GREY,
BLACK
}
枚举之间存在差异(灰色/灰色) - 但是在编译时无法捕捉到这个错字。如果系统使用数据库存储或消息传递,并且必须根据其值在枚举值之间进行转换,则会产生麻烦。
我希望我可以这样做:
public enum GrayscaleColors {
AllColors.WHITE,
AllColors.GRAY,
AllColors.BLACK
}
但这似乎不可能。
您可以声明构造函数,并比较构造函数中的名称:
public enum GrayscaleColors {
WHITE(AllColors.WHITE),
GREY(AllColors.GRAY),
BLACK(AllColors.BLACK);
GrayscaleColors(AllColors ac) {
if (!name().equals(ac.name()) throw new IllegalArgumentException();
}
}
或者,您可以简单地使用AllColors.valueOf
:
public enum GrayscaleColors {
WHITE,
GREY,
BLACK;
GrayscaleColors() {
// Will throw if no corresponding name exists.
AllColors.valueOf(name());
}
}
或者,当然,您可以编写单元测试来检查匹配的名称。