简体   繁体   English

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

[英]Java cast Long to Enum type issue

I had a little problem with casting Java long type to Enum type and can't find a solution how to do that. 将Java long类型转换为Enum类型时出现了一些问题,无法找到解决方法。

Here is what I'm using : 这是我正在使用的:

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

    private int value;
    private DataType(int i){
        this.value = i;
    }
}

and I need to do something like this: 我需要做这样的事情:

DataType dataType;
String thiz = "1";
long numb = Long.parseLong(thiz);
dataType = numb;

The error that I get says: 我得到的错误说:

Convert numb to DataType or convert dataType to long. 将numb转换为DataType或将dataType转换为long。

Second Scenario: 第二种情景:

I have this : 我有这个 :

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.

I tried to convert thiz to String[] and use valueOf,but 我试图将thiz转换为String []并使用valueOf,但是

Any suggestions how to get the thinks to work? 有任何建议如何使思想工作?

Thanks in advance! 提前致谢!

Enum already provides a unique integer for each of it's instances. Enum已经为每个实例提供了一个唯一的整数。 Check out ordinal() . 查看ordinal() (Note that it's zero-based though.) (请注意,它基于零。)

If you need to go from a long to a DataType you can do 如果您需要从longDataType您可以这样做

DataType dataType;
String thiz;
long numb = Long.parseLong(thiz);
dataType = DataType.values()[(int) numb];

A complete list of conversions from and to enum constants, strings and integers can be found in this answer: 在这个答案中可以找到枚举常量,字符串和整数的完整转换列表:

In addition to @aioobe's answer , you could roll your own getInstance method. 除了@ aioobe的答案 ,你可以推出自己的getInstance方法。 This would provide more flexibility, since you wouldn't be dependent on the ordinal. 这将提供更大的灵活性,因为您不会依赖序数。

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

        return null;
    }
}

If for some reason you need to assign the numbers yourself and thereby can't use aioobe's good solution, you can do something like the following: 如果由于某种原因您需要自己分配数字,从而无法使用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");
 }

The static method getByValue() searches for the DataType with the provided number. 静态方法getByValue()使用提供的数字搜索DataType

Correct answer from aioobe. 来自aioobe的正确答案。 Maybe some other concerns ? 也许其他一些问题?

You could be better of using int instead of long, for the enum index. 对于枚举索引,你最好使用int而不是long。 It could be like : 它可能像:

String indexAsString;
int index = Integer.parseInt(indexAsString)-1;
DataType dataType = DataType.values()[index];

Please note the "-1", as arrays are zero-based while your index is one-based. 请注意“-1”,因为数组是从零开始的,而您的索引是从1开始的。

ordinal() will work if the numbers you are passing to the enum are indexes and not some arbitrary code, like resolution or number of chars in a line. 如果传递给枚举的数字是索引而不是某些任意代码,如行中的分辨率或字符数,则ordinal()将起作用。

I'd extends the enum with an accesor method for the value, a resolution index and a static method that resolves a number into a Enum value. 我使用值的访问方法,分辨率索引和将数字解析为枚举值的静态方法扩展了枚举。 Here you go... 干得好...

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

    DataType(int i){
       this.value=i;
    }

    static final Map<Integer,DataType> inverseIndex;
    static {
        inverseIndex = new HashMap<Integer,DataType> ();
        for (DataType dt:DataType.values()) {
            inverseIndex.put(dt.getValue(), dt);
        }   
    }

    public int getValue() {
        return value;
    }

    public static DataType resolve(int number) {
        return inverseIndex.get(number);
    }
}

Note that this solution won't work is your map Enum-value is not bijective, so you may only have distinct values for the enums in your enumType. 请注意,此解决方案不起作用是您的地图枚举值不是双射的,因此您的enumType中的枚举可能只有不同的值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM