Skip to content

Instantly share code, notes, and snippets.

@cestrand
Created March 30, 2018 08:09
Show Gist options
  • Save cestrand/bd9740a93f5f06d28888bf6b1d6e890e to your computer and use it in GitHub Desktop.
Save cestrand/bd9740a93f5f06d28888bf6b1d6e890e to your computer and use it in GitHub Desktop.
Java's `enum` on String values
package com.company;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.util.concurrent.atomic.AtomicLong;
@RestController
@SpringBootApplication
public class StringEnumController {
private static final String template = "Hello, %s!";
private final AtomicLong counter = new AtomicLong();
public static void main(String[] args) {
SpringApplication.run(StringEnumController.class, args);
}
@RequestMapping("/")
public String index(
@RequestParam(value = "name", defaultValue = "World") String name,
@RequestParam(value = "color", defaultValue = Color.defaultColor) String color
) {
Color col = Color.search(color);
return String.format(template, name);
}
public enum Color {
WHITE("white"), BLUE("blue");
public static final String defaultColor = "white";
private final String text;
Color(final String s) {
this.text = s;
}
public static Color search(final String s) throws EnumConstantNotPresentException {
for (Color col : Color.values()) {
if (s.equals(col.toString())) {
return col;
}
}
throw new EnumConstantNotPresentException(Color.class, '"' + s + '"');
}
@Override
public String toString() {
return text;
}
}
}
@cestrand
Copy link
Author

cestrand commented Mar 30, 2018

If search fails it throws nice

java.lang.EnumConstantNotPresentException: com.company.StringEnumController$Color."red"
	at com.company.StringEnumController$Color.search(StringEnumController.java:47) ~[classes/:na]
	at com.company.StringEnumController.index(StringEnumController.java:59) ~[classes/:na]

where double-quotes indicate it failed on search by value.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment