RFR: 8318144: Match on enum constants with body compiles but fails with MatchException

Chen Liang liach at openjdk.org
Fri Nov 3 23:53:06 UTC 2023


On Fri, 3 Nov 2023 16:26:49 GMT, Jan Lahoda <jlahoda at openjdk.org> wrote:

> For code like:
> 
> enum E {A {}, B {} }
> Object o = E.A;
> switch (o) {
>      case E.A -> System.err.println(o);
>      default -> System.err.println("default");
> }
> 
> 
> The result is `default`, not `A`, due to incorrect classes being compared. Thanks for @liach for noting the solution here:
> https://github.com/openjdk/jdk/pull/16489#discussion_r1381411165

Marked as reviewed by liach (Author).

src/java.base/share/classes/java/lang/runtime/SwitchBootstraps.java line 399:

> 397:                 Class<?> clazz = label.constantType().resolveConstantDesc(lookup);
> 398: 
> 399:                 if (!(value instanceof Enum<?> enumValue) ||

Minor comment: If we are more concerned about performance when the enum is in a mix-and-match with other types (say primitives etc.), we can move the `instanceof` test before the `constantType().resolveConstantDesc()` to avoid a Class lookup.

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

PR Review: https://git.openjdk.org/jdk/pull/16499#pullrequestreview-1713656471
PR Review Comment: https://git.openjdk.org/jdk/pull/16499#discussion_r1382291935


More information about the compiler-dev mailing list