java - 开关编译错误

标签 java byte switch-statement bytebuffer

我看了其他问题,还是想不通。为什么它不让我用 switch 语句编译这段代码?我收到典型错误“case expressions must be constant expressions”的错误。我正在尝试从消息中打开字节。由于速度问题,我想使用开关并尽量不进行任何转换,即从 int 到 byte。我的 Utils 类包含一个带有 A、B、C...的枚举 PID。我想打开这些,但我收到的消息以字节为单位。

public class SomeClass extends Thread {
    public static final byte myCase1 = (byte) Utils.PID.A.ordinal();
    public static final byte myCase2 = (byte) Utils.PID.B.ordinal();
    public static final byte myCase3 = (byte) Utils.PID.C.ordinal();

    private double[] findAllData(ByteBuffer message) {

        byte[] byteBuffer = new byte[9000];
        // parse through and find all PIDs
        for(int i=0 ;i < message.capacity(); i++) {
            message.position(i);

            switch (message.get(i)) {
            case myCase1 : break;  // Compiler errors at the case statements
            case myCase2 : break;// Compiler errors at the case statements
            case myCase3 : break;// Compiler errors at the case statements
            }
    }
}


//  Utility class
public class Utils {
    public enum PID { A,B,C };
}

最佳答案

尽管 myCase1 是一个常量,但它在编译时不是已知的常量。

相反,我会打开枚举

private static final Utils.PID[] PIDS = Utils.PID.values();

private double[] findAllData(ByteBuffer message) {

    byte[] byteBuffer = new byte[9000];
    // parse through and find all PIDs
    for (int i = 0; i < message.capacity(); i++) {
        message.position(i);

        switch (PIDS[message.get(i)]) {
            case A:
                break;
            case B:
                break;
            case C:
                break;
        }
    }

例如这是行不通的

private static final int NUM1 = Integer.getInteger("num1"); // from command line properties
private static final int NUM2 = Integer.getInteger("num2"); // from command line properties

switch(num) {
  case NUM1: break;
  case NUM2: break;
}

关于java - 开关编译错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8125460/

相关文章:

java - java中如何将char映射到int

java - 始终从对象读取值或将其存储在变量中并使用它是一种好习惯吗?

java - String get/set 是线程安全的吗?

php - 在 PHP 中将 UDP 数据包数据转换为人类可读的形式

objective-c - 将字节存储到正确的包装器中

c++ - 将字节数组转换为 time_t

java - 为什么字符的 switch/case 不起作用?

java - java处理大数时的算术错误

java - java中的停用词和词干分析器

tcl "switch -glob"与变量不匹配