Java switch语句:需要常量表达式,但它是常量 [英] Java switch statement: Constant expression required, but it IS constant

查看:682
本文介绍了Java switch语句:需要常量表达式,但它是常量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以,我正在研究这个有一些静态常量的类:

So, I am working on this class that has a few static constants:

public abstract class Foo {
    ...
    public static final int BAR;
    public static final int BAZ;
    public static final int BAM;
    ...
}

然后,我想要一种方法来获取基于常量的相关字符串:

Then, I would like a way to get a relevant string based on the constant:

public static String lookup(int constant) {
    switch (constant) {
        case Foo.BAR: return "bar";
        case Foo.BAZ: return "baz";
        case Foo.BAM: return "bam";
        default: return "unknown";
    }
}

然而,当我编译时,我得到需要常量表达式每个3个案例标签上的错误。

However, when I compile, I get a constant expression required error on each of the 3 case labels.

我知道编译器需要在编译开关的编译时间,但为什么不是 Foo.BA _ 常量?

I understand that the compiler needs the expression to be known at compile time to compile a switch, but why isn't Foo.BA_ constant?

推荐答案


我知道编译器需要在编译时知道表达式来编译一个开关,但为什么不是Foo.BA_常量?

I understand that the compiler needs the expression to be known at compile time to compile a switch, but why isn't Foo.BA_ constant?

虽然从字段初始化后执行的任何代码的角度看它们是常量,但它们不是编译时常量 JLS要求;请参阅§15.28常量表达式用于定义常量表达式所需的内容。这是指§4.12.4最终变量它定义了一个常量变量,如下所示:

While they are constant from the perspective of any code that executes after the fields have been initialized, they are not a compile time constant in the sense required by the JLS; see §15.28 Constant Expressions for a definition of what is required of a constant expression. This refers to §4.12.4 Final Variables which defines a "constant variable" as follows:


我们调用一个原始类型或类型String的变量,它是最终的并且用编译时常量表达式(第15.28节)一个常量变量。变量是否是常量变量可能对类初始化(第12.4.1节),二进制兼容性(第13.1节,第13.4.9节)和明确赋值(第16节)有影响。

We call a variable, of primitive type or type String, that is final and initialized with a compile-time constant expression (§15.28) a constant variable. Whether a variable is a constant variable or not may have implications with respect to class initialization (§12.4.1), binary compatibility (§13.1, §13.4.9) and definite assignment (§16).

在您的示例中,Foo.BA *变量没有初始值设定项,因此不符合常量变量的条件。修复很简单;将Foo.BA *变量声明更改为具有编译时常量表达式的初始值设定项。

In your example, the Foo.BA* variables do not have initializers, and hence do not qualify as "constant variables". The fix is simple; change the Foo.BA* variable declarations to have initializers that are compile-time constant expressions.

这篇关于Java switch语句:需要常量表达式,但它是常量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆