开发者

Android Java cast long to enum problem

开发者 https://www.devze.com 2023-03-31 08:10 出处:网络
I have an issue with Java cast long type to Enum\'s type. I\'m using this code : public enum RPCPacketDataType {

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 va开发者_如何学JAVAlue;
    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:

public static RPCPacketDataType valueOf(int value) {
    ...
}

Then call that from your case statement. Given that the value can only be an integer, you should almost certainly be using Integer.parseInt instead of Long.parseLong.

How you implement the valueOf method is up to you - you could iterate through the EnumSet of all values trying to find a match, or create a HashMap from Integer to RPCPacketDataType, 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 valueOf is passed a value which doesn't correspond to any enum value - one option is to return null (and probably test for that explicitly in the calling code); another is to throw an exception.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号