I know this question is a few years old, but as Java 8 has, in the meantime, brought us Optional
, I thought I'd offer up a solution using it (and Stream
and Collectors
):
public enum PcapLinkType {
DLT_NULL(0),
DLT_EN3MB(2),
DLT_AX25(3),
/*snip, 200 more enums, not always consecutive.*/
// DLT_UNKNOWN(-1); // <--- NO LONGER NEEDED
private final int value;
private PcapLinkType(int value) { this.value = value; }
private static final Map<Integer, PcapLinkType> map;
static {
map = Arrays.stream(values())
.collect(Collectors.toMap(e -> e.value, e -> e));
}
public static Optional<PcapLinkType> fromInt(int value) {
return Optional.ofNullable(map.get(value));
}
}
Optional
is like null
: it represents a case when there is no (valid) value. But it is a more type-safe alternative to null
or a default value such as DLT_UNKNOWN
because you could forget to check for the null
or DLT_UNKNOWN
cases. They are both valid PcapLinkType
values! In contrast, you cannot assign an Optional<PcapLinkType>
value to a variable of type PcapLinkType
. Optional
makes you check for a valid value first.
Of course, if you want to retain DLT_UNKNOWN
for backward compatibility or whatever other reason, you can still use Optional
even in that case, using orElse()
to specify it as the default value:
public enum PcapLinkType {
DLT_NULL(0),
DLT_EN3MB(2),
DLT_AX25(3),
/*snip, 200 more enums, not always consecutive.*/
DLT_UNKNOWN(-1);
private final int value;
private PcapLinkType(int value) { this.value = value; }
private static final Map<Integer, PcapLinkType> map;
static {
map = Arrays.stream(values())
.collect(Collectors.toMap(e -> e.value, e -> e));
}
public static PcapLinkType fromInt(int value) {
return Optional.ofNullable(map.get(value)).orElse(DLT_UNKNOWN);
}
}