Indicating the javac version (Re: Eager enum class initialization with enum switch)
Tagir Valeev
amaembo at gmail.com
Wed Feb 20 03:33:46 UTC 2019
Hello!
This problem seems to exist always. At least I observe the same
behavior in all javac version I have starting from javac 1.6.0_45 up
until the latest javac 13-ea+8. The relevant part of spec seems not to
be changed much between versions as well. Nevertheless I agree that I
should have been more specific. Sorry for this.
With best regards,
Tagir Valeev.
On Wed, Feb 20, 2019 at 4:24 AM Alex Buckley <alex.buckley at oracle.com> wrote:
>
> 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