简体   繁体   English

Java:case表达式必须是常量表达式

[英]Java: case expressions must be constant expressions

I am using enum with values and when I try to use SmartCard.MessageType.SC_CONN.getValue() in the switch case I am getting the error 我正在使用带有值的枚举,当我尝试在切换情况下使用SmartCard.MessageType.SC_CONN.getValue()时,出现错误

case expressions must be constant expressions case表达式必须是常量表达式

public class SmartCard {
    public enum MessageType {
        /** 0x00 Acknowledge of message */
        SC_ACKP(0),
        /** 0x01 Connect to the smart card */
        SC_CONN(1),
        /** 0x02 Request ATR attributes of smart card */
        SC_ATTR(2),
        /** 0x03 Send data to smart card */
        SC_SEND(3);

        private int value;

        MessageType(int value) {
            this.value = value;
        }


        public int getValue() {
            return this.value;
        }

    };

    }

public class TCPServer {

public static void main(String args[]) throws Exception {
      }
    private static void handleMessage(int packetType, int dataLen, byte[] receiveMessage, Socket clientSocket,
            SmartCard smartCard) {
        ByteBuffer answerBuffer = null;
        int value = SmartCard.MessageType.SC_CONN.getValue();
        String preferredProtocol = "";
        switch (packetType) {
        case 0:
            break;
        case value:
            break;
        case 2: 

        }

    }
}

在Java中,case语句必须是一个编译时常数,而value不是,而是在运行时分配的。

The second case of the switch statement is written wrongly. switch语句的第二种情况写错了。 value cannot be used here. value不能在这里使用。 The value of every case must be constant. 每种情况的值必须恒定。 Let's see what the JLS says. 让我们看看JLS怎么说。

Section 14.11 第14.11节

SwitchStatement:
    switch ( Expression ) SwitchBlock

SwitchBlock:
    { SwitchBlockStatementGroupsopt SwitchLabelsopt }

SwitchBlockStatementGroups:
    SwitchBlockStatementGroup
    SwitchBlockStatementGroups SwitchBlockStatementGroup

SwitchBlockStatementGroup:
    SwitchLabels BlockStatements

SwitchLabels:
    SwitchLabel
    SwitchLabels SwitchLabel

SwitchLabel:
    case ConstantExpression :
    case EnumConstantName :
    default :

EnumConstantName:
    Identifier

Look at the definition for a SwitchLabel . 查看SwitchLabel的定义。 The thing after case must either be a ConstantExpression or an EnumConstantName . case之后的东西必须是ConstantExpressionEnumConstantName value is neither of those. value都不是这些。

One solution to this problem is to use if...else if...else statements. 解决此问题的一种方法是使用if...else if...else语句。

if (packetType == 0) {

} else if (packetType == value) {

} else if (packetType == 2) {

}

If you really want to keep the switch statement, do an if check in the default branch. 如果您确实要保留switch语句,请在默认分支中执行if检查。

switch (packetType) {
case 0:
    break;
case 2: 
    break;
default:
    if (packetType == value) { ... }
    break;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM