java - 是否可以从资源常量中声明一个字符串以在 switch 情况下使用?

标签 java android string constants

我有这段代码,旨在将字符串从 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 关于该主题的说法:

JLS §14.11 :

Every case label has a case constant, which is either a constant expression or the name of an enum constant.

JLS §15.28 :

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.
  • ....

JLS §14.12.4 :

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

<小时/>

为什么?

  1. 基本类型的 switch 语句的实现使用需要在代码中使用文字常量的 JVM 指令。

  2. 在字符串和枚举情况下,切换是使用编译器/运行时系统根据情况构造的代码/数据结构来执行的。如果情况不恒定,则编译器无法构造它们。

  3. 如果 switch 常量的值不是常量,则编译器无法正确分析明确赋值和可达性。

前两个可以被视为“只是”实现细节。最后一点更为根本。放宽规则会破坏语言。

关于java - 是否可以从资源常量中声明一个字符串以在 switch 情况下使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38542221/

相关文章:

java - 使用什么策略来确定 JSON 或 XML?

java - 使用JAVA可以快速从网站下载图片吗

java - 找不到 : org. gradle.api.internal.artifacts.ivyservice.ivyresolve.VersionInfo(java.lang.String) 的匹配构造函数

java - 使用套接字通过 Python 将图像文件从 Android 手机发送到 PC

java - 使用 Java 从网页中读取文本

android - 如何在 Flutter 中创建一个按钮表并从中随机选择任何按钮?

android - 在尝试发送 SMS 之前检查 Android 中的网络覆盖范围

r - 如何使用正则表达式替换 '\U'?

python - 在 Python 字符串中同时包含单引号和双引号

delphi - 在 Delphi 中将非定界文本转换为名称/值对