枚举中的空静态方法

Dha*_*n.S 0 java enums android

  • 我找到了一些核心概念的代码,但我需要知道这个枚举类背后的概念.
  • 请任何人都可以告诉枚举类和静态方法是如何工作的,并且也可以为这个概念提供合适的示例.

码:

enum EBtnSts
{
  static
  {
    ePlayBtn = new EBtnSts("ePlayBtn", 1);

    EBtnSts[] arrayOfEBtnSts = new EBtnSts[0];
    arrayOfEBtnSts[0] = ePlayBtn;

  }
}
Run Code Online (Sandbox Code Playgroud)

Roh*_*ain 5

这是一个疯狂的使用static initializer,你应该真的避免.首先,这肯定会引发ArrayIndexOutOfBounds异常.

EBtnSts[] arrayOfEBtnSts = new EBtnSts[0];  // Creates an array of length 0
arrayOfEBtnSts[0] = ePlayBtn;    // You can't access any index of 0 length array.
Run Code Online (Sandbox Code Playgroud)

其次,该代码实现了enum一个普通的类.避免.变量ePlayBtn应该是枚举常量.在enum包含您在构造函数中传递的值中应该有2个字段.并且不要像这样调用构造函数.

此外,阵列的创建完全没有意义.您可以使用values()您的方法直接获取枚举常量数组enum.

enum被更好地实现为:

enum EBtnSts {
    E_PLAY_BTN("ePlayBtn", 1);

    private final String value;
    private final int id;

    private EBtnSts(String value, int id) {
        this.value = value;
        this.id = id;
    }

    private final EBtnSts[] VALUES = values();
}
Run Code Online (Sandbox Code Playgroud)

您可以在此处了解有关枚举类型的更多信息.