Is this valid Java code?
I am using Eclipse and he is quite 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 I am running it on on crashes is on the line marked above. By mistake, think of the BSOD equivalent. Is there something wrong with my code, or do I need to chase the Java VM developers for my platform?
EDIT:
Ok, thanks for your answers. This turned out to be a bug in the Java VM. To quote the developer, "gloomyandy",
This is a known issue with interfaces that have a static initializer. It gets fixed in current development releases ...
a source to share
I don't see any problem with this code, other than this if you are using Java5 or higher you are better off using an enum:
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 :-)
}
}
Update: to recreate the enum value from its byte representation, you need to add MessageType
as follows (adapted from Effective Java, 2nd Ed. Item 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);
}
a source to share
As everyone was told, this should work.
You can try this:
public class MessageTest implements MessageType
{
public static void main(String[] args)
{
int b = MESSAGES.length; // no MessageType here
}
}
( MessageType
not required as the class implements it).
I would prefer the method suggested by Peter Torek.
a source to share