Indicating the javac version (Re: Eager enum class initialization with enum switch)

Alex Buckley alex.buckley at oracle.com
Tue Feb 19 21:22:16 UTC 2019


Anyone on this list has a good chance of contributing to multiple 
versions of javac, not just the version in the current JDK GA release. 
(GA: General Availability)  So, when raising questions about javac, 
please indicate the version of javac that you're using. `javac -version` 
should be enough. `java -version` is fine too.

Also, please indicate the edition of the JLS or JVMS that you're 
referring to.

Alex

On 2/16/2019 12:59 AM, Tagir Valeev wrote:
> 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