这是有效的 Java 代码吗?
我正在使用 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 中的一个错误。引用开发商的话,“gloomyandy”,
这是具有静态初始值设定项的接口的一个已知问题。它已在当前开发版本中修复...
I'm using Eclipse, and it is perfectly happy with the following code:
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
}
}
However, the platform that I'm running it on crashes at the line marked above. By crash, think an equivalent of a BSOD. Is there anything wrong with my code, or do I need to pursue the developers of the Java VM for my platform?
EDIT:
Ok, thanks for your responses. It turned out to be a bug in the Java VM. To quote the developer, 'gloomyandy',
This is a known problem with interfaces that have a static initializer. It is fixed in the current development builds...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我没有看到这段代码有任何问题,除了如果您使用 Java5 或更高版本,您最好使用枚举:
更新:从其字节表示重新创建枚举值,您需要使用以下内容补充
MessageType
(改编自Effective Java,第二版第 31 项):I don't see any problem with this code, other than that if you are using Java5 or above, you would be better off using an enum:
Update: to recreate the enum value from its byte representation, you need to supplement
MessageType
with the following (adapted from Effective Java, 2nd Ed. Item 31):看起来很合理...
如果您从类中删除“implements MessageType”怎么办,它仍然会崩溃吗?
Seems reasonable...
What if you take the "implements MessageType" off of your class, does it still crash?
代码本身是完美的。我可以在我的Win7机器上完美地编译和运行它(使用Java6);听起来你正在使用一些不寻常的系统?
The code itself is perfectly sound. I can compile and run it perfectly fine on my Win7 machine (with Java6); it sounds like you're using some unusual system?
正如每个人所说,它应该有效。
您可以尝试这个:(
不需要
MessageType
,因为该类正在实现它)。我仍然更喜欢方式彼得·托洛克建议道。
As everybody told, it should work.
You can try this one:
(
MessageType
is not needed since the class is implementing it).I still would prefer the way Péter Török suggested.