1
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”值的原因是我不想每次都评估它应该是什么。我从一开始就知道,所以我只想保存值,因此当调用时它不是评估,而只是将值传回

我知道还有其他方法可以解决这个问题:

  1. 修改构造函数以接受参数:

    老鼠(假),猫(假),蝙蝠(真);

    // Constructor
    Batman(boolean isMatch)
    {
        this.isMatch = isMatch;
    }
    
  2. 更改 isMatch()

public boolean isMatch()
  {
      return (this.compareTo(Bat) == 0) ? true : false;
  }

任何建议都会很棒。

谢谢

4

3 回答 3

3

正如其他人所说,您不能在构造函数中引用特定的 Enum 值。显而易见的解决方案是这样写:

public enum Batman
{
    Rat, Cat, Bat;


    public boolean isMatch()
    {
        return this == Bat;
    }
}

(顺便说一句,Enum 不需要等于)

但如果评估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;
    }
}

(注意符号和必须保护而不是私有{{ }}的事实,以便 Bat 实例可以访问它。)isMatch

于 2013-02-15T14:55:44.020 回答
2

书有效的Java

不允许枚举构造函数访问枚举的静态字段,编译时常量字段除外。这个限制是必要的,因为这些静态字段在构造函数运行时还没有被初始化。

于 2013-02-15T14:52:12.127 回答
1

您绝对不能在构造函数中引用任何特定的 ENUM,因为它需要在您想要引用它时创建,而您只是在创建它!
我会选择选项 1,因为您将依赖的特定知识置于枚举本身的内部实现之外。

于 2013-02-15T14:48:01.423 回答