Java SE 11 带有三元运算符的字符串最终变量在 Switch Case 表达式中不算作常量变量

Java SE 11 String Final Variable with Ternary Operator Does Not Count as a Constant Variable in Switch Case Expression

我遇到了以下代码不起作用的问题。我 运行 Java SE 11 (11.0.8), Eclipse 2020-06, Windows 10.

中的代码

将字符串最终变量与三元运算符一起使用:不起作用

public class Tester {
    public static void main(String[] args) {
        
        String switchVar = "abc";
        final String caseStr = true ? "abc" : "def";    
        switch (switchVar) {
            case caseStr: System.out.println("Doesn't work");
        }
    }
}

它有一个编译时错误:java.lang.Error: Unresolved compilation problem: case expressions must be constant expressions


但是,根据JLS §4.12.4 and JLS §15.28,String类型可以是final变量,三元运算符也可以算作常量表达式。

A constant variable is a final variable of primitive type or type String that is initialized with a constant expression.

A constant expression is an expression denoting a value of primitive type or a String that does not complete abruptly and is composed using only the following:

...

  • The ternary conditional operator ? :

  • Simple names that refer to constant variables


我做了一些更多的测试,结果表明如果不结合在一起,这些点中的任何一个都有效。

直接用常量表达式作为case常量:没问题

public class Tester {
    public static void main(String[] args) {
        
        String switchVar = "abc";
        switch (switchVar) {
            case true ? "abc" : "def": System.out.println("works");
        }
    }
}

使用不带三元运算符的字符串常量变量:没问题

public class Tester {
    public static void main(String[] args) {
        
        String switchVar = "abc";
        
        final String VAR_A = "a";
        final String VAR_BC = "bc";
        final String CASE = VAR_A + VAR_BC;
        
        switch (switchVar) {
            case CASE : System.out.println("works");
        }
    }
}

将 int 与三元运算符一起使用而不是 String:没问题

public class Tester {
    public static void main(String[] args) {
        
        int switchVar = 10;
        final int CASE = 3 > 2 ? 10 : 0;
        
        switch (switchVar) {
            case CASE : System.out.println("works");
        }
    }
}

有人能帮帮我吗?

在其他人的帮助下,现在确定这是eclipse的一个bug。

我已将错误报告给 eclipse。 (Bugzilla – Bug 566332)