JLS - "anywhere within" static initializer

Kay, Andrew (Research Student) kaya3 at aston.ac.uk
Fri Aug 17 18:35:14 UTC 2018


Hi,

I've noticed something slightly misleading in the JLS, section 8.7 (Static Initializers):
https://docs.oracle.com/javase/specs/jls/se10/html/jls-8.html#jls-8.7

It is a compile-time error if a return statement (§14.17<https://docs.oracle.com/javase/specs/jls/se10/html/jls-14.html#jls-14.17>) appears anywhere within a static initializer.

It is a compile-time error if the keyword this (§15.8.3<https://docs.oracle.com/javase/specs/jls/se10/html/jls-15.html#jls-15.8.3>) or the keyword super (§15.11<https://docs.oracle.com/javase/specs/jls/se10/html/jls-15.html#jls-15.11>, §15.12<https://docs.oracle.com/javase/specs/jls/se10/html/jls-15.html#jls-15.12>) or any type variable declared outside the static initializer, appears anywhere within a static initializer.

The plain meaning of "anywhere within" would forbid the following code, which has return, this and super within a static initializer (via a local class declaration), but compiles without errors (using version 10.0.2).

class A {
    static int x;
    static {
        class B {
            B() { super(); }
            int y = 1;
            int c() {
                return this.y;
            }
        }
        x = new B().c();
    }
}

This could be resolved by adding something like "…anywhere within a static initializer, unless it appears within a local class declaration contained in that static initializer". There are at least two more cases which should be permitted - anonymous class declarations, and return statements in lambda body blocks.

Thanks,
-Andrew Kay


More information about the jls-jvms-spec-comments mailing list