Java › Enums
How would you implement a custom enum that also functions as a lookup table (mapping an external code to a constant), such as parsing an HTTP status code string into an enum constant, handling unknown values gracefully?
AdvancedAnswer
Rather than relying on the built-in valueOf() (which throws IllegalArgumentException for any unrecognized name and requires an exact case-sensitive match to the constant's declared identifier), a more robust approach adds a custom static lookup method backed by a private static Map<String, EnumType> built once during static initialization, mapping external representations (which might differ from the enum's own Java identifier naming conventions) to the corresponding constant, with an explicit fallback (like returning an UNKNOWN sentinel constant, or throwing a custom, more descriptive exception) for values that don't match any known constant.
public enum HttpStatus {
OK(200), NOT_FOUND(404), SERVER_ERROR(500), UNKNOWN(-1);
private final int code;
private static final Map<Integer, HttpStatus> BY_CODE = new HashMap<>();
static {
for (HttpStatus status : values()) { BY_CODE.put(status.code, status); }
}
HttpStatus(int code) { this.code = code; }
public static HttpStatus fromCode(int code) {
return BY_CODE.getOrDefault(code, UNKNOWN); // graceful fallback instead of throwing
}
}Real-world example An HTTP client library parsing status codes from external API responses uses a custom fromCode() lookup method (built on a precomputed static Map) rather than relying on the enum's own name-based valueOf(), gracefully handling any unexpected or non-standard status code by falling back to an UNKNOWN constant instead of throwing an exception that would crash response parsing entirely.