Created
March 30, 2018 08:09
-
-
Save cestrand/bd9740a93f5f06d28888bf6b1d6e890e to your computer and use it in GitHub Desktop.
Java's `enum` on String values
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
If
search
fails it throws nicewhere double-quotes indicate it failed on
search
by value.