[jdk19] RFR: JDK-8289894: A NullPointerException thrown from guard expression

Jan Lahoda jlahoda at openjdk.org
Thu Jul 7 14:55:13 UTC 2022


Consider the following code:

public class SwitchGuard {
    public static void main(String... args) {
        test(null);
    }
    private static void test(Object o) {
        switch (o) {
            case null, String s when s.isEmpty() -> System.err.println("OK.");
            default -> {}
        }
    }
}


In the current specification, the guard should not be invoked when `o` is `null`, but javac will invoke it, for historical reasons.

Also, as opposed to JDK 18/JEP 420, `case null, <pattern>` is allowed for parenthesized pattern when the parenthesized pattern encloses (directly or via other parenthesized patterns) a type pattern.

The patch proposed here strives to fix both of these problems.

-------------

Commit messages:
 - JDK-8289894: A NullPointerException thrown from guard expression

Changes: https://git.openjdk.org/jdk19/pull/120/files
 Webrev: https://webrevs.openjdk.org/?repo=jdk19&pr=120&range=00
  Issue: https://bugs.openjdk.org/browse/JDK-8289894
  Stats: 69 lines in 6 files changed: 55 ins; 0 del; 14 mod
  Patch: https://git.openjdk.org/jdk19/pull/120.diff
  Fetch: git fetch https://git.openjdk.org/jdk19 pull/120/head:pull/120

PR: https://git.openjdk.org/jdk19/pull/120


More information about the compiler-dev mailing list