Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

enums

jls

This is from Effective Java :

// Implementing a fromString method on an enum type
  private static final Map<String, Operation> stringToEnum
      = new HashMap<String, Operation>();

  static { // Initialize map from constant name to enum constant
    for (Operation op : values())
      stringToEnum.put(op.toString(), op);
  }

  // Returns Operation for string, or null if string is invalid
  public static Operation fromString(String symbol) {
    return stringToEnum.get(symbol);
  }

Note that the Operation constants are put into the stringToEnum map from a static block that runs after the constants have been created. Trying to make each constant put itself into the map from its own constructor would cause a compilation error. This is a good thing, because it would cause a NullPointerException if it were legal. Enum constructors aren’t permitted to access the enum’s static fields, except for compile-time constant fields. This restriction is necessary because these static fields have not yet been initialized when the constructors run.

My question is regarding the line :

"Note that the Operation constants are put into the stringToEnum map from a static block that runs after the constants have been created" .

I thought the static block gets executed before the constructor runs. The are actually executed during class load time.

What am I missing here ?

like image 662
Geek Avatar asked Aug 02 '12 11:08

Geek


1 Answers

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.

like image 66
Adam Monos Avatar answered Sep 21 '22 23:09

Adam Monos