Singleton via enum way is lazy initialized?

enum instance fields are not “initialized by a compile-time constant expression”. They
can’t be, because only String and primitive types are possible types for a compile-time constant expression.

That means that the class will be initialized when INSTANCE is first accessed (which is exactly the desired effect).

The exception in the bold text above exists, because those constants (static final fields initialized with a compile-time constant expression) will effectively be inlined during compilation:

class A {
  public static final String FOO = "foo";

  static {
    System.out.println("initializing A");
  }
}

class B {
  public static void main(String[] args) {
    System.out.println(A.FOO);
  }
}

Executing class B in this example will not initialize A (and will not print “initializing A”). And if you look into the bytecode generated for B you’ll see a string literal with the value “foo” and no reference to the class A.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)