Enum ValueOf Lookup With Unknown Input
Parse user-supplied tokens into enum constants with valueOf, trim and uppercase the input, and fail with the full list of valid constants.
Code
import java.util.Arrays;
import java.util.Locale;
public class FormatParser {
enum ExportFormat {
CSV, JSON, XLSX;
// Lookup: parse case-insensitively and fail with an error listing the valid constants instead of returning null
static ExportFormat parse(String token) {
try {
return valueOf(token.trim().toUpperCase(Locale.ROOT));
} catch (IllegalArgumentException bad) {
throw new IllegalArgumentException("unknown format '" + token
+ "', expected one of " + Arrays.toString(values()));
}
}
}
public static void main(String[] args) {
for (String raw : new String[] {" csv ", "json"}) {
System.out.println(raw.trim() + " -> " + ExportFormat.parse(raw));
}
try {
ExportFormat.parse("xml");
} catch (IllegalArgumentException e) {
System.out.println(e.getMessage());
}
}
}How the snippet works
Everything happens inside the classes FormatParser and ExportFormat and the functions parse and main.
for (String raw : new String[] {" csv ", "json"}) is the loop that carries the per-item work. Invalid states are rejected up front: it throws IllegalArgumentException instead of continuing with bad data.
What to watch for
- The imports (if any) point only at standard-library modules.
Applying it
Entry signature: static ExportFormat parse(String token)
main sequences parse; executing the file runs that flow once.
Statements that matter
return valueOf(token.trim().toUpperCase(Locale.ROOT));
throw new IllegalArgumentException("unknown format '" + token
+ "', expected one of " + Arrays.toString(values()));
FAQ
- How does the snippet fail?
- `IllegalArgumentException` is raised at the guard, so invalid state never reaches the main logic.
- How do you run Enum ValueOf Lookup With Unknown Input?
- Direct execution is enough; the script has no external requirements.
Report a problem with this exampleOpens a pre-filled issue on GitHub.