Порядок выполнения статических блоков в типе Enum по отношению к конструктору

Это из Эффективной 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.

Мой вопрос касается строки:

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

Я думал, что статический блок выполняется до запуска конструктора. Они фактически выполняются во время загрузки класса.

Что мне здесь не хватает?

12
задан Geek 2 August 2012 в 12:04
поделиться