Eager enum class initialization with enum switch
Tagir Valeev
amaembo at gmail.com
Sat Feb 16 08:59:22 UTC 2019
Hello!
Consider the following program (Test.java):
class Test {
enum A{
X;
static { System.out.println("A is initialized!"); }
}
enum B{
Y;
static { System.out.println("B is initialized!"); }
}
static void testA(A a) { switch(a) {} }
static void testB(B b) { switch(b) {} }
public static void main(String[] args) {
testA(A.X);
}
}
When I compile it via javac and run it I see:
A is initialized!
B is initialized!
Despite the fact that testB is never called, and no references to the
B enum actually used during the program execution. According to JLS
12.4.1 B should not be initialized. Am I missing something?
If I use the Eclipse compiler, I got the expected result
A is initialized!
This occurs because javac spins an additional class Test$1 which holds
enum constant mapping and its static initializer initializes mappings
for all the enums used. In contrast, Eclipse creates synthetic static
methods (one per enum) in the same Test class which lazily initialize
the corresponding fields. Such approach better follows the spec, to my
opinion.
So is this javac problem or I don't understand the spec?
With best regards,
Tagir Valeev.
More information about the compiler-dev
mailing list