I have an issue with Java cast long type to Enum’s type.
I’m using this code :
public enum RPCPacketDataType {
PT_JSON(1),
PT_BINARY(2);
private int value;
RPCPacketDataType(int i){
this.value=i;
}
public int getNumericType(){
return value;
}
}
static RPCPacketDataType tmpPacket_packetType;
And I need to do something like this :
case 2:
{
long intVal = Long.parseLong(thisPart);
if(intVal == 0){
isBad = true; break;
}
tmpPacket_packetType=intVal;
break;
}
where thisPart is just a string : String thisPart;
And the error says : Type mismatch: cannot convert from long to RPCCommucatorDefines.RPCPacketDataType
Any suggestions how to fix that?
You need to write a method, probably in RPCPacketDataType:
Then call that from your case statement. Given that the value can only be an integer, you should almost certainly be using
Integer.parseIntinstead ofLong.parseLong.How you implement the
valueOfmethod is up to you – you could iterate through theEnumSetof all values trying to find a match, or create aHashMapfrom Integer toRPCPacketDataType, or potentially just an array (with validation). It will depend on what’s in your enum, and how many values there are to look through.Note that you should also consider what to do if
valueOfis passed a value which doesn’t correspond to any enum value – one option is to returnnull(and probably test for that explicitly in the calling code); another is to throw an exception.