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

标签 string eclipse switch-statement java-11 constant-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.4JLS §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的一个错误。
我已向 Eclipse 报告了该错误。 ( Bugzilla – Bug 566332 )

关于string - 带有三元运算符的 Java SE 11 字符串最终变量在 Switch Case 表达式中不算作常量变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63563294/

相关文章:

java - 以字符串形式循环遍历字母表

python - 如何打破 PEP8 合规性的长字符串?

python - 安卓工作室 : IncorrectOperationException when 'Add as Library' is clicked whilst trying to configure Google Apps Endpoints client libraries

javascript - case user.length < 4;控制台日志 ("nametoo short :(");休息;为什么这不起作用?

c# - 在 C# 中使用 if/else 和 switch-case 之间有什么显着区别吗?

r - 在 dplyr 中使用 c() 聚合字符串汇总或聚合

c - 如何在 C 中将元素添加到字符串数组?

Java/Eclipse 64 位性能

java - Android-选项卡 Activity 出现错误

ruby - 。任何?在 case block 内未按预期进行评估