Java强制转换为枚举类型问题

And*_*oid 3 java enums casting primitive-types long-integer

将Java long类型转换为Enum类型时出现了一些问题,无法找到解决方法.

这是我正在使用的:

public enum DataType {
    IMAGES(1),
    VIDEOS(2);

    private int value;
    private DataType(int i){
        this.value = i;
    }
}
Run Code Online (Sandbox Code Playgroud)

我需要做这样的事情:

DataType dataType;
String thiz = "1";
long numb = Long.parseLong(thiz);
dataType = numb;
Run Code Online (Sandbox Code Playgroud)

我得到的错误说:

将numb转换为DataType或将dataType转换为long.

第二种情景:

我有这个 :

static String[] packetType;
String tmp=incomingData.toString(); // where incomingData is byte[]
int lastLoc = 0;
int needsSize = packetFieldSizes[tmpCurrentField-1]; // where packetFieldSizes,tmpCurrentField are integers.
thiz=tmp.substring(lastLoc, needsSize);    

packetType=thiz;  // packetType = thiz copy; where thiz is the same as used above.
Run Code Online (Sandbox Code Playgroud)

我试图将thiz转换为String []并使用valueOf,但是

有任何建议如何使思想工作?

提前致谢!

aio*_*obe 12

Enum已经为每个实例提供了一个唯一的整数.退房ordinal().(请注意,它基于零.)

如果你需要从a long到a,DataType你可以做到

DataType dataType;
String thiz;
long numb = Long.parseLong(thiz);
dataType = DataType.values()[(int) numb];
Run Code Online (Sandbox Code Playgroud)

在这个答案中可以找到枚举常量,字符串和整数的完整转换列表:

  • 对于每个枚举常量都有自己的`id`是一个很好的做法,在这种情况下,你持有这个ID,因为当你在其间插入新的常量时,`ordinal()`可能会改变同一个项目. (3认同)

mre*_*mre 6

除了@ aioobe的答案,你可以推出自己的getInstance方法.这将提供更大的灵活性,因为您不会依赖序数.

public enum DataType {
    .
    .
    public static final DataType getInstance(final int i){
        for(DataType dt: DataType.values()){
            if(dt.value == i){
                return dt;
            }
        }

        return null;
    }
}
Run Code Online (Sandbox Code Playgroud)


mus*_*iKk 5

如果由于某种原因您需要自己分配数字,从而无法使用aioobe的良好解决方案,您可以执行以下操作:

public enum DataType {
    IMAGES(1),
    VIDEOS(2);

 private final int value;
 private DataType(int i){
    this.value=i;
 }
 public static DataType getByValue(int i) {
     for(DataType dt : DataType.values()) {
         if(dt.value == i) {
             return dt;
         }
     }
     throw new IllegalArgumentException("no datatype with " + i + " exists");
 }
Run Code Online (Sandbox Code Playgroud)

静态方法使用提供的数字getByValue()搜索DataType.