我有这段代码,旨在将字符串从 Spinner 项转换为整数,以便在应用程序的另一部分中使用。当我在 switch case 中有常量字符串时,这种方法效果很好,但后来我想将这些硬编码字符串移动到 Strings.xml 资源中,以将它们与逻辑分开。这就是我遇到麻烦的地方,因为 Java 希望字符串保持不变。
我尝试将字符串设为最终的,但没有任何区别。所以我的问题是,是否有可能以某种方式使资源中的字符串成为常量,以使它们可以在像下面代码 fragment 中的那样的 switch 情况下使用?
public int getPositionFromText(String text) {
// The string representations of the different score methods.
String[] scoreOptions = getResources().getStringArray(R.array.scoreOptions);
final String three = scoreOptions[0];
final String four = scoreOptions[1];
final String five = scoreOptions[2];
switch(text) {
case three:
return 0;
case four:
return 1;
case five:
return 2;
default:
return 0;
}
}
最佳答案
无法解决“需要常量表达式”编译错误。 Java 语言规范要求开关表达式是编译时常量表达式。
我的建议是构建一个 HashMap
。使用资源常量值作为键,使用分数/位置作为值。
以下是 JLS 关于该主题的说法:
Every case label has a
case
constant, which is either a constant expression or the name of anenum
constant.
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:
- Literals of primitive type and literals of type
String
.- The additive operators
+
and-
.- Simple names that refer to constant variables .
- Qualified names of the form
<TypeName> . <Identifier>
that refer to constant variables.- ....
<小时/>A constant variable is a
final
variable of primitive type or typeString
that is initialized with a constant expression.
为什么?
基本类型的 switch 语句的实现使用需要在代码中使用文字常量的 JVM 指令。
在字符串和枚举情况下,切换是使用编译器/运行时系统根据情况构造的代码/数据结构来执行的。如果情况不恒定,则编译器无法构造它们。
如果 switch 常量的值不是常量,则编译器无法正确分析明确赋值和可达性。
前两个可以被视为“只是”实现细节。最后一点更为根本。放宽规则会破坏语言。
关于java - 是否可以从资源常量中声明一个字符串以在 switch 情况下使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38542221/