Accessing static fields inside enum

Generally I have learnt that static blocks/initializations inside a Java class get executed first during compilation. But trying to access the static field inside the enum gives me the error

Cannot refer to the static enum field ExportToReports.Animal.num within an initializer.

Why does this error occur as the static variable must have been initialised?

public enum Animal{
    cat(2), dog(3);
    int id, number;
    static int num = 5;
    Animal(int id)
    {
        this.id = id;
        this.number = Animal.num;
    }   
}

So does this mean that when it comes to enum static blocks doesn't get executed first??Pls explain


A simple workaround is to put the static field inside a static inner class:

enum Foo{
  RED,GREEN,BLUE;

  private final int value;
  private Foo(){
     this.value = ++ Bar.heresMyStaticField;
  }

  static class Bar{
     private static int heresMyStaticField;
  }
}

Whether you should do that is an entirely different question.


Static initialization occurs when the class is loaded for the first time. cat and dog , as enums, are treated statically for initialization purposes and are initialized first (as they are declared above num ). When they are initialized any references in their constructor must already be initialized. You can make this work by declaring the num field final which initializes num at compile time:

final static int num = 5;

If num needs to change value after initialization, then you would need to move it out of the enum and to another class.

链接地址: http://www.djcxy.com/p/38066.html

上一篇: 枚举和静态变量在构造函数中

下一篇: 在枚举中访问静态字段