Lyke Lyke - 2 years ago 110
Java Question

Convert integer value to matching Java Enum

I've an enum like this:

public enum PcapLinkType {
/*snip, 200 more enums, not always consecutive.*/
private final int value;

PcapLinkType(int value) {
this.value= value;

Now I get an int from external input and want the matching input - throwing an exception if a value does not exist is ok, but preferably I'd have it be
in that case.

int val = in.readInt();
PcapLinkType type = ???; /*convert val to a PcapLinkType */

Answer Source

You would need to do this manually, by adding a a static map in the class that maps Integers to enums, such as

private static final Map<Integer, PcapLinkType> intToTypeMap = new HashMap<Integer, PcapLinkType>();
static {
    for (PcapLinkType type : PcapLinkType.values()) {
        intToTypeMap.put(type.value, type);

public static PcapLinkType fromInt(int i) {
    PcapLinkType type = intToTypeMap.get(Integer.valueOf(i));
    if (type == null) 
        return PcapLinkType.DLT_UNKNOWN;
    return type;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download