Java Data Type How to - Check if enum contains a given string


We would like to know how to check if enum contains a given string.


//from ww  w .  ja  va 2s. c  o m
import java.util.EnumSet;

public class Main {

  static enum Choices {
    a1, a2, b1, b2

  public static <E extends Enum<E>> boolean contains(Class<E> _enumClass,
      String value) {
    try {
      return EnumSet.allOf(_enumClass)
          .contains(Enum.valueOf(_enumClass, value));
    } catch (Exception e) {
      return false;

  public static void main(String[] args) {
    for (String value : new String[] { "a1", "a3", null }) {
      System.out.println(contains(Choices.class, value));