简体   繁体   中英

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

I am trying to get Enum constant through value assigned to it but don't know if there is any built in API to do this. My enum looks like this :

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;
    }
}

How do I get enum constant VIDEO_BW_2_MBPS through value "2000000" assigned to it ? I understand that if values are sequential like 0,1,2,3, I can use VideoBandwidth.values()[index] but how do I get the constant in case when values cannot be used as 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);
}

Of course, you can also store the enum values in an internal Map, for example, if you want to avoid the iteration and the array creation.

Implement your own method that iterate over all the constants and returns the appropriate one or null /some exception.

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

Iterate just once! define a static Map and fill it in a static block at load time.

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;
}

Use a map:

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);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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