Dec 13

Often we need to lookup an enum value based on some property. While we can be tempted to massage the value into a String we can then convert to an Enum, this method is dangerous and should be avoided as it makes assumptions about the string values of your enums.

Instead we can enhance our Enum to provide a method to lookup the required Enum value as shown in the following example.

enum MyEnum {
	A("thisIsA"), B("thisIsB"), C("thisIsC");
	
	// Our enum has a label property
	
	private String label = null;
	
	// We want to be able to lookup enum value based on the label property
	// This map holds all enums keyed on 'label'
	
	private static Map<String, MyEnum> lookup = new HashMap<String, MyEnum>();
	static {
		
		// Populate out lookup when enum is created
		
		for (MyEnum e : MyEnum.values()) {
			lookup.put(e.label(), e);
		}
	}

	// Provide a method to lookup up enum with matching label
	
	public static MyEnum get(String label) {
		return lookup.get(label);
	}
	
	String label() {
		return label;
	}

	MyEnum(String label) {
		this.label = label;
	}
}

We can then easily lookup the enum value for a given label string using the following

String s = "thisIsB";
Enum e = MyEnum.get(s);    // this will get set to MyEnum.B

written by objects \\ tags: ,