枚举 - 静态和实例块

时间:2012-07-10 18:24:41

标签: java enums static-block

我已经了解到,在Java中,静态块在初始化类时执行,并且在构造每个类的实例之前执行实例块。我总是在实例块之前看到要执行的静态块。为什么案例与enums相反?

任何人都可以向我解释一下示例代码的输出:

enum CoffeeSize {

    BIG(8), LARGE(10),HUGE(12),OVERWHELMING();
    private int ounces ;

    static {
        System.out.println("static block ");
    }
    {
        System.out.println("instance block");
    }

    private CoffeeSize(int ounces){
        this.ounces = ounces;
        System.out.println(ounces);
    }
    private CoffeeSize(){
        this.ounces = 20;
        System.out.println(ounces);
    }

    public int getOunces() {
        return ounces;
    }
} 

输出:

实例块
8
实例块
10个
实例块
12个
实例块
20个
静态块

4 个答案:

答案 0 :(得分:28)

您需要知道枚举值是包含该枚举类型实例的静态字段,静态字段的初始化顺序取决于它们的位置。 见这个例子

class SomeClass{
    public SomeClass() { System.out.println("creating SomeClass object"); }
}

class StaticTest{
    static{ System.out.println("static block 1"); }
    static SomeClass sc = new SomeClass();
    static{ System.out.println("static block 2"); }

    public static void main(String[] args) {
        new StaticTest();
    }
}

输出

static block 1
creating SomeClass object
static block 2

现在因为枚举值始终位于枚举类型的开头,所以它们将始终在任何静态初始化块之前被调用,因为其他所有内容都只能在枚举值之后声明。
但是初始化枚举值(在类初始化时发生)它们的构造函数被调用,正如你所说的那样,非静态初始化块在每个构造函数的开头执行,这就是你看到它们的原因:

  • 表示每个枚举值
  • 并且在任何静态初始化块之前。

答案 1 :(得分:9)

很晚才积累Pshemo's answer。下面(编译)代码的输出如下:

8
10
Foo
static block 
Bar

因此首先执行枚举常量初始化(如Pshemo所说,它们总是隐式staticfinal,请参见第二个块引用)然后初始化显式声明为static的所有字段。如上所述,语言规范说明了类初始化期间的执行顺序以及枚举常量:

  

Next, execute either the class variable initializers and static initializers of the class, or the field initializers of the interface, in textual order, as though they were a single block.

     

In addition to the members that an enum type E inherits from Enum, for each declared enum constant with the name n, the enum type has an implicitly declared public static final field named n of type E. These fields are considered to be declared in the same order as the corresponding enum constants, before any static fields explicitly declared in the enum type.


class StaticTest {
    enum CoffeeSize {
        BIG(8), LARGE(10);
        private int ounces;

        static Foo foo = new Foo();
        static { System.out.println("static block "); }
        static Bar bar = new Bar();

        private CoffeeSize(int ounces){
            this.ounces = ounces;
            System.out.println(ounces);
        }
    }
    public static void main(String[] args) {
        CoffeeSize cs = CoffeeSize.LARGE;
    }
}

class Foo { public Foo() { System.out.println("Foo"); } }
class Bar { public Bar() { System.out.println("Bar"); } }

答案 2 :(得分:1)

1。 枚举类型是一种类型,其字段由一组固定的常量组成。常见示例包括罗盘方向(NORTH,SOUTH,EAST和WEST的值)和星期几。

2。它们是静态最终常量,因此所有字母都是大写字母。

3. 一旦JVM加载了类,就会初始化静态变量。

有关详细信息,请参阅此链接:

http://docs.oracle.com/javase/1.5.0/docs/guide/language/enums.html

答案 3 :(得分:1)

使用字节码来解决这个问题。

import java.util.ArrayList;
import java.util.List;

public enum EnumDemo {
    ONE(1), TWO(2);

    private final static List<Integer> vals;
    static {
        System.out.println("fetch instance from static");
        vals = new ArrayList<>();
        EnumDemo[] values = EnumDemo.values();
        for (EnumDemo value : values) {
            vals.add(value.val);
        }
    }

    private int val;
    EnumDemo(int val){
        this.val = val;
        System.out.println("create instance:" + val);
    }

}

使用javac编译到类文件,然后javap -c EnumDemo.class,得到了这个:

Compiled from "EnumDemo.java"
public final class EnumDemo extends java.lang.Enum<EnumDemo> {
  public static final EnumDemo ONE;

  public static final EnumDemo TWO;

  public static EnumDemo[] values();
    Code:
       0: getstatic     #1                  // Field $VALUES:[LEnumDemo;
       3: invokevirtual #2                  // Method "[LEnumDemo;".clone:()Ljava/lang/Object;
       6: checkcast     #3                  // class "[LEnumDemo;"
       9: areturn       

  public static EnumDemo valueOf(java.lang.String);
    Code:
       0: ldc_w         #4                  // class EnumDemo
       3: aload_0       
       4: invokestatic  #5                  // Method java/lang/Enum.valueOf:(Ljava/lang/Class;Ljava/lang/String;)Ljava/lang/Enum;
       7: checkcast     #4                  // class EnumDemo
      10: areturn       

  static {};
    Code:
       0: new           #4                  // class EnumDemo
       3: dup           
       4: ldc           #16                 // String ONE
       6: iconst_0      
       7: iconst_1      
       8: invokespecial #17                 // Method "<init>":(Ljava/lang/String;II)V
      11: putstatic     #18                 // Field ONE:LEnumDemo;
      14: new           #4                  // class EnumDemo
      17: dup           
      18: ldc           #19                 // String TWO
      20: iconst_1      
      21: iconst_2      
      22: invokespecial #17                 // Method "<init>":(Ljava/lang/String;II)V
      25: putstatic     #20                 // Field TWO:LEnumDemo;
      28: iconst_2      
      29: anewarray     #4                  // class EnumDemo
      32: dup           
      33: iconst_0      
      34: getstatic     #18                 // Field ONE:LEnumDemo;
      37: aastore       
      38: dup           
      39: iconst_1      
      40: getstatic     #20                 // Field TWO:LEnumDemo;
      43: aastore       
      44: putstatic     #1                  // Field $VALUES:[LEnumDemo;
      47: getstatic     #8                  // Field java/lang/System.out:Ljava/io/PrintStream;
      50: ldc           #21                 // String fetch instance from static
      52: invokevirtual #15                 // Method java/io/PrintStream.println:(Ljava/lang/String;)V
      55: new           #22                 // class java/util/ArrayList
      58: dup           
      59: invokespecial #23                 // Method java/util/ArrayList."<init>":()V
      62: putstatic     #24                 // Field vals:Ljava/util/List;
      65: invokestatic  #25                 // Method values:()[LEnumDemo;
      68: astore_0      
      69: aload_0       
      70: astore_1      
      71: aload_1       
      72: arraylength   
      73: istore_2      
      74: iconst_0      
      75: istore_3      
      76: iload_3       
      77: iload_2       
      78: if_icmpge     109
      81: aload_1       
      82: iload_3       
      83: aaload        
      84: astore        4
      86: getstatic     #24                 // Field vals:Ljava/util/List;
      89: aload         4
      91: getfield      #7                  // Field val:I
      94: invokestatic  #26                 // Method java/lang/Integer.valueOf:(I)Ljava/lang/Integer;
      97: invokeinterface #27,  2           // InterfaceMethod java/util/List.add:(Ljava/lang/Object;)Z
     102: pop           
     103: iinc          3, 1
     106: goto          76
     109: return        
}

因此,枚举实例是静态实例,并且在头部。

相关问题