Explain Codes LogoExplain Codes Logo

Override valueof() and toString() in Java enum

java
enum
custom-values
reflection
Anton ShumikhinbyAnton Shumikhin·Mar 2, 2025
TLDR
public enum Color { RED, GREEN, BLUE; @Override public String toString() { // No upper cases in my life! return name().toLowerCase(); } public static Color valueOfIgnoreCase(String name) { // Go uppercase or go home! return Color.valueOf(name.toUpperCase()); } }

Override toString() to control the display format of an enum. Create a valueOfIgnoreCase method for case-insensitive matching, because valueOf() is final and immovable like a stubborn mule.

Customize enum strings with spaces

public enum PaintingStyle { IMPRESSIONISM("Impressionism"), // Monet, is that you? CUBISM("Cubism"), // Picasso, you square! SURREALISM("Surrealism"); // Dali, stop watching the clock! private final String styleName; PaintingStyle(String styleName) { this.styleName = styleName; } @Override public String toString() { // No more screaming art movement names! return styleName; } public static PaintingStyle fromStringWithSpaces(String str) { // Loop through like you're in an art gallery. for (PaintingStyle style : values()) { if (style.styleName.equalsIgnoreCase(str.trim())) { return style; } } // Sorry, no abstract art today. throw new IllegalArgumentException("No constant with text " + str + " found"); } }

Handle spaces and custom values like a pro by mapping strings to enum values with fancy loop de loop. Guard your masterpiece from unforeseen exceptions when there is mismatch. Because art is subjective, but your code is not!

Improve lookup performance by mapping strings to enum

import java.util.Map; import java.util.stream.Collectors; import java.util.stream.Stream; public enum Flavor { VANILLA("Vanilla"), // Standard as a kitchen backsplash. CHOCOLATE("Chocolate"), // Oh, the sweet smell of optimization. STRAWBERRY("Strawberry"); // Did someone say anchors in smoothie? private static final Map<String, Flavor> FLAVOR_MAP = Stream.of(Flavor.values()) .collect(Collectors.toMap(Object::toString, e -> e)); private final String flavorName; Flavor(String flavorName) { this.flavorName = flavorName; } @Override public String toString() { return flavorName; } public static Flavor fromString(String flavorName) { // It's like flavor Google search. return FLAVOR_MAP.getOrDefault(flavorName, null); } }

Leave slow and clunky iterations behind. Map your enum values to strings in record time, just like going from zero to hundred in flavor town.

Retrieve custom value, use error handling, and rock the interface

public static <E extends Enum<E> & CustomValueEnum> E fromCustomValue(String customValue, Class<E> enumClass) { // Like finding a needle in a haystack, but EASY. return Arrays.stream(enumClass.getEnumConstants()) .filter(e -> e.getCustomValue().equals(customValue)) .findAny() .orElseThrow(() -> new IllegalArgumentException("That's a no-no: " + customValue)); } public interface CustomValueEnum { // Every enum has a dream... to be a custom value! String getCustomValue(); }

Interfaces and Enums: a match made in heaven. Custom values at your fingertips, with specialised error handling is the cherry on top!

Play safe, avoid reflection risks

Reflective code is like a shiny new toy, but beware, it can lead to security risks and end up as an alien in your codebase if not handled correctly! Always remember, safe code is happy code!

Tweak your enum with advanced utilities

Customize your enum to your heart's content:

  • Filters: To strip away anything unnecessary.
  • Maps: To make sure you always find what you’re looking for.
  • Collectors: To compile everything you need in one place.

Feeling overwhelmed? Fear not, Google’s Guava library is here to your rescue!