Community
Participate
Working Groups
(3.1RC3) javac forbids accessing static fields within a constructor. The class below fails to compile with the error: "Test.java:9: illegal reference to static field from initializer". Eclipse compiles it just fine. It's a reasonable thing to at least warn about, as any static initializer on the field won't execute until after all the enum values have been constructed. It's also a bit of a pain when everything works in Eclipse and then javac breaks :( Here's the code: public enum Test { SomeValue; static int asd; private Test() { asd=5; } }
Indeed this seems to be a bug in Eclipse compiler. From the JLS (page 257), It is a compile-time error to reference a non-constant (ยง15.28) static field of an enum type from its constructors, instance initializer blocks, or instance variable initializer expressions.
Only implicit references are forbidden, following would be fine: public enum Test { SomeValue; static int asd; private Test() { Test.asd=5; } }
Aha - that's good to know, thanks :)
Note that qualified references may yield default values for fields, it simply bypasses the normal initialization. e.g. class X { static int FOO = X.BAR; static int BAR = 2; } --> FOO will be 0.
Clarifying: it actually bypasses the check for initialization.
Added EnumTest#test115-116. Fixed. Will be released to 3.1 maintenance branch as soon as it is created.
Fix is in Scope#getBinding(char[]...), it ensures that when finding a static field in enum, it isn't located inside offending context.
Fixed in 3.1 maintenance branch
*** Bug 102265 has been marked as a duplicate of this bug. ***
*** Bug 92165 has been marked as a duplicate of this bug. ***
Verified in 3.2 M1 with build I20050808-2000.
*** Bug 108905 has been marked as a duplicate of this bug. ***
*** Bug 110403 has been marked as a duplicate of this bug. ***
Verified using M20050923-1430 for 3.1.1
*** Bug 149042 has been marked as a duplicate of this bug. ***