Execution order of of static blocks in an Enum type w.r.t to constructor

前端 未结 3 734
栀梦
栀梦 2020-12-19 00:01

This is from Effective Java :

// Implementing a fromString method on an enum type
  private static final Map stringToEnum
      = ne         


        
相关标签:
3条回答
  • 2020-12-19 00:26

    Operation constants are static fields created in the static block in the appearing order.

    static { 
        // instantiate enum instances here
        ...
        // Initialize map from constant name to enum constant     
        for (Operation op : values())       
           stringToEnum.put(op.toString(), op);   
    } 
    
    0 讨论(0)
  • 2020-12-19 00:28

    I understand your question as: why is there a guarantee that the enum constants will be initialised before the static block is run. The answer is given in the JLS, and a specific example is given in #8.9.2.1, with the following explanation:

    static initialization occurs top to bottom.

    and the enums constants are implicitly final static and are declared before the static initializer block.

    EDIT

    The behaviour is not different from a normal class. The code below prints:

    In constructor: PLUS
    PLUS == null MINUS == null
    
    In constructor: MINUS
    PLUS != null MINUS == null
    
    In static initialiser
    PLUS != null MINUS != null
    
    In constructor: after static
    PLUS != null MINUS != null
    
    public class Operation {
    
        private final static Operation PLUS = new Operation("PLUS");
        private final static Operation MINUS = new Operation("MINUS");
    
        static {
            System.out.println("In static initialiser");
            System.out.print("PLUS = " + PLUS);
            System.out.println("\tMINUS = " + MINUS);
        }
    
        public Operation(String s) {
            System.out.println("In constructor: " + s);
            System.out.print("PLUS = " + PLUS);
            System.out.println("\tMINUS = " + MINUS);
        }
    
        public static void main(String[] args) {
            Operation afterStatic = new Operation ("after static");
        }    
    }
    
    0 讨论(0)
  • 2020-12-19 00:37

    The static blocks execute in order of appearance (you can have multiple static blocks), when the class loader loads the class, eg. it runs before the constructor.

    0 讨论(0)
提交回复
热议问题