This is a very wide-spread enum singleton code:
public enum enumClazz{
INSTANCE
enumClazz(){
//do something
}
}
and a bunch o
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
.
The third point with bold style clarify that if the field is 'static final', the initialzation of the field is happened at complie-time
Not exactly - it only applies to "static fields that are final and initialized by a compile-time constant expression":
static final String = "abc"; //compile time constant
static final Object = new Object(); //initialised at runtime
In your case, the singleton will be initialised when the enum class is loaded, i.e. the first time enumClazz
is referenced in your code.
So it is effectively lazy, unless of course you have a statement somewhere else in your code that uses the enum.