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”值的原因是我不想每次都评估它应该是什么。
我从一开始就知道,所以我只想保存这个值,因此当调用时它不是评估
但只是将值传回
我知道还有其他方法可以解决这个问题:
修改构造函数以接受参数:
老鼠(假),猫(假), bat (真);
// Constructor Batman(boolean isMatch) { this.isMatch = isMatch; }
改变 isMatch()
public boolean isMatch() { return (this.compareTo(Bat) == 0) ? true : false; }
任何建议都会很棒。
谢谢
最佳答案
正如其他人所说,您不能在构造函数中引用特定的枚举值。显而易见的解决方案是这样写:
public enum Batman
{
Rat, Cat, Bat;
public boolean isMatch()
{
return this == Bat;
}
}
(顺便说一句,你不需要使用 Enum 的 equals)
但是如果评估 this == Bat
真的困扰你,你可以覆盖 Bat 的 isMatch:
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
必须被保护而不是私有(private)的事实,以便 Bat 实例可以访问它.)
关于java - 识别构造函数中的特定枚举,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14897104/