Uploaded image for project: 'JDK'
  1. JDK
  2. JDK-8345953

JEP 492: instantiating local classes in a different static context should not be allowed

XMLWordPrintable

    • b03

        JEP 492 spec: https://cr.openjdk.org/~gbierman/jep492/jep492-20241101/specs/flexible-constructor-bodies-jls.html

        Assertion:
        If C occurs in a static context, then i has no immediately enclosing instance. Let S be the nearest static method declaration, static field declaration, or static initializer that encloses the declaration of C. If the nearest static method declaration, static field declaration, or static initializer that encloses the class instance creation expression is not S, then a compile-time error occurs.

        Class Local1 in the code sample below is declared as part of the static field initializer (in a static context), and it's instantiated in a different static context.
        The instance creation is supposed to fail in this case, but it succeeds.

        class Test {
            static int field = switch (1) {
                case 1 -> {
                    class Local1 {
                        class Local2 {
                            public static void m() {
                                new Local1(); // does not fail
                            }
                        }
                    }
                    yield 1;
                }
                default -> 2;
            };
        }

              mcimadamore Maurizio Cimadamore
              ymaslyanko Yuriy Maslyanko
              Votes:
              0 Vote for this issue
              Watchers:
              4 Start watching this issue

                Created:
                Updated:
                Resolved: