我正在使用Eclipse,并且对以下代码非常满意:

public interface MessageType
{
    public static final byte   KICK     = 0x01;
    public static final byte   US_PING  = 0x02;
    public static final byte   GOAL_POS = 0x04;
    public static final byte   SHUTDOWN = 0x08;
    public static final byte[] MESSAGES = new byte[] {
        KICK,
        US_PING,
        GOAL_POS,
        SHUTDOWN
    };
}

public class MessageTest implements MessageType
{
    public static void main(String[] args)
    {
        int b = MessageType.MESSAGES.length;    //Not happy
    }
}

但是,我正在运行它的平台在上面标记的线路上崩溃。通过崩溃,认为相当于BSOD。我的代码有什么问题,还是我需要为我的平台追求Java VM的开发人员?


编辑:

好的,谢谢您的回复。事实证明,这是Java VM中的一个错误。引用开发人员的“忧郁”,

这是具有静态初始化器的接口的已知问题。它是在当前开发构建中固定的...

有帮助吗?

解决方案

除了使用Java5或更高版本外,我没有看到此代码的任何问题,最好使用枚举:

public enum MessageType
{
    KICK     (0x01),
    US_PING  (0x02),
    GOAL_POS (0x04),
    SHUTDOWN (0x08);

    private byte value;
    MessageType(byte value) { this.value = value; }
    byte getValue() { return value; }
}

public class MessageTest
{
    public static void main(String[] args)
    {
        int b = MessageType.values().length;    //Should be happy :-)
    }
}

更新: 要从其字节表示中重新创建枚举价值,您需要补充 MessageType 使用以下(改编自生效Java,第二版。项目31):

private static final Map<Byte, MessageType> byteToEnum = new HashMap<Byte, MessageType>();

static { // Initialize map from byte value to enum constant
  for (MessageType type : values())
    byteToEnum.put(type.getValue(), type);
}

// Returns MessageType for byte, or null if byte is invalid
public static MessageType fromByte(Byte byteValue) {
  return byteToEnum.get(byteValue);
}

其他提示

似乎是合理的...

如果您将“实现MessageType”从班级中脱颖而出,该怎么办,它仍然崩溃吗?

代码本身是完美的。我可以在Win7机器(使用Java6)上进行编译和运行;听起来您正在使用一些不寻常的系统?

正如每个人所说的那样,它应该起作用。
您可以尝试一下:

public class MessageTest implements MessageType
{
    public static void main(String[] args)
    {
        int b = MESSAGES.length;    // no MessageType here
    }
}

(MessageType 由于班级正在实施)。
我还是更喜欢 道路 PéterTörök建议。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top