簡體   English   中英

如何從Java中分配給它們的值中檢索枚舉常量?

[英]How to retrieve Enum Constants from values assigned to them in Java?

我試圖通過分配給它的值來獲取Enum常量,但是不知道是否有內置的API可以做到這一點。 我的枚舉看起來像這樣:

public enum VideoBandwidth {

    VIDEO_BW_AUTO(-1),
    VIDEO_BW_OFF(0),
    VIDEO_BW_2_MBPS(2000000),
    VIDEO_BW_500_KBPS(500000),
    VIDEO_BW_250_KBPS(250000);

    private final int bandwidth;

    private VideoBandwidth (final int value) {
        bandwidth = value;
    }

    public int getValue() {
        return bandwidth;
    }
}

如何通過為其分配值“ 2000000”來獲取枚舉常量VIDEO_BW_2_MBPS? 我知道如果值是連續的(如0、1、2、3),則可以使用VideoBandwidth.values()[index],但是當值不能用作Index時,如何獲取常數呢?

public static VideoBandwidth withValue(int value) {
    for (VideoBandwidth v : values()) {
        if (v.bandwidth == value) {
             return v;
        }
    }
    throw new IllegalArgumentException("no VideoBandwidth with value " + value);
}

當然,例如,如果要避免迭代和數組創建,也可以將枚舉值存儲在內部Map中。

實現自己的方法,該方法遍歷所有常量並返回適當的一個或null / some異常。

public VideoBandwidth valueOf(int bandwidth) {
    for (VideoBandwidth videoBandwidth : values()) {
        if (videoBandwidth.bandwidth == bandwidth)
            return videoBandwidth;
    }
    throw new RuntimeException();
}

重復一次! 定義靜態地圖,並在加載時將其填充到靜態塊中。

final static Map<Integer, VideoBandwidth> cache = new HashMap<>();
static {
    for(VideoBandwidth e: VideoBandwidth.values()) {
        cache.put(e.getValue(), e);
    }
}

public static VideoBandwidth fromValue(int value) {
    VideoBandwidth videoBandwidth = cache.get(value);
    if(videoBandwidth == null) {
        throw new RuntimeException("No such enum for value: " + value);
    }
    return videoBandwidth;
}

使用地圖:

public enum VideoBandwidth {

    VIDEO_BW_AUTO(-1),
    VIDEO_BW_OFF(0),
    VIDEO_BW_2_MBPS(2000000),
    VIDEO_BW_500_KBPS(500000),
    VIDEO_BW_250_KBPS(250000);

    private final int bandwidth;
    private static final Map<Integer, VideoBandwidth> map = new HashMap<Integer, VideoBandwidth>();

    private VideoBandwidth (final int value) {
        bandwidth = value;
        map.put(value, this);
    }

    public int getValue() {
        return bandwidth;
    }

    public static VideoBandwidth valueOf(int bandWidth) {
        return map.get(bandWidth);
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM