public enum Batman
{
Rat, Cat, Bat;
private boolean isMatch;
// Constructor
Batman()
{
this.isMatch = (this.compareTo(Bat) == 0) ? true : false;
}
public boolean isMatch()
{
return this.isMatch;
}
}
对于构造函数行,我得到错误: 无法在初始值设定项中引用静态枚举字段Batman.Bat
我主要是想弄清楚是否可以在构造函数中识别特定的ENUM 我想保存“isMatch”值的原因是我不想每次评估它应该是什么。 我知道从一开始就知道了,所以我只想保存这个值,因此在进行调用时它不是评估 但只是简单地传递价值
我知道还有其他方法可以解决这个问题:
修改构造函数以接受参数:
大鼠(假),猫(假),蝙蝠(真);
// Constructor
Batman(boolean isMatch)
{
this.isMatch = isMatch;
}
更改isMatch()
public boolean isMatch() { return (this.compareTo(Bat) == 0) ? true : false; }
任何建议都会很棒。
由于
答案 0 :(得分:3)
正如其他人所说,你不能在构造函数中引用特定的枚举值。显而易见的解决方案是写下这个:
public enum Batman
{
Rat, Cat, Bat;
public boolean isMatch()
{
return this == Bat;
}
}
(顺便说一句,你不需要与Enum等于)
但如果评估this == Bat
真的困扰你,你可以覆盖isMatch for Bat:
public enum Batman
{
Rat, Cat,
Bat {
@Override
public boolean isMatch() {
return true;
}
};
public boolean isMatch()
{
return false;
}
}
这样,你没有比较,而是使用覆盖枚举值的方法。
这是一个变种,只是为了好玩:
public enum Batman
{
Rat, Cat,
Bat {{
this.isMatch = true;
}};
protected boolean isMatch = false;
public boolean isMatch()
{
return isMatch;
}
}
(请注意符号{{
}}
以及必须保护isMatch
而不是私有的事实,以便Bat实例可以访问它。)
答案 1 :(得分:2)
来自 Book Effective Java :
不允许枚举构造函数访问枚举的静态字段, 除了编译时常量字段。这种限制是必要的 因为这些静态字段尚未初始化 施工人员。
答案 2 :(得分:1)
你绝对不能在构造函数中引用任何特定的ENUM,因为当你想引用它并且你只是创建它时需要创建它! 我会选择选项1,因为你将依赖外部的特定知识用于枚举本身的内部实现。