大家好,又见面了,我是你们的朋友全栈君。如果您正在找激活码,请点击查看最新教程,关注关注公众号 “全栈程序员社区” 获取激活教程,可能之前旧版本教程已经失效.最新Idea2022.1教程亲测有效,一键激活。
Jetbrains全系列IDE稳定放心使用
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”;
}
}
However, when I compile, I get a constant expression required error on each of the 3 case labels.
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?
解决方案
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?
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:
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).
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.
发布者:全栈程序员-用户IM,转载请注明出处:https://javaforall.cn/187918.html原文链接:https://javaforall.cn
【正版授权,激活自己账号】: Jetbrains全家桶Ide使用,1年售后保障,每天仅需1毛
【官方授权 正版激活】: 官方授权 正版激活 支持Jetbrains家族下所有IDE 使用个人JB账号...