java - 识别构造函数中的特定枚举

标签 java constructor enums

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. 修改构造函数以接受参数:

    老鼠(假),猫(假), bat (真);

    // Constructor
    Batman(boolean isMatch)
    {
        this.isMatch = isMatch;
    }
    
  2. 改变 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/

相关文章:

java - 从 jTable 中的多个选定行获取数据

java - 如何从 akka 中的不同系统查找对远程参与者的引用?

java - "..."在 Java 中被使用?

c++ - 使用类模板范围中的枚举而不指定模板参数

c# - 如何在 C# 中枚举枚举?

java - 当我尝试初始化 GoogleMap 对象时,出现 NullPointerException

java - RecyclerView 中的 AsyncTask 抛出 You can not start a load for a destroyed Activity on Callback

Java:我正在尝试使用我创建的名为 Date 的类中的方法显示日期,但是当我尝试将其运行到另一个类中时,数字将不会显示

c# - 抽象类的构造函数要求返回类型

c# - 如果 A 和 B 是枚举类型,为什么我可以将 A[] 转换为 B[]?