Java Data Type How to - Get enum name from enum value








Question

We would like to know how to get enum name from enum value.

Answer

import java.util.HashMap;
import java.util.Map;
/*from  w w  w  .j a  va  2s .c  o  m*/
public class Main {
  public static void main(String[] args) {
    MyEnum enum1 = MyEnum.Choice1;
    System.out.println("enum1==>" + String.valueOf(enum1));
    MyEnum enum2 = MyEnum.getByValue(enum1.getValue());
    System.out.println("enum2==>" + String.valueOf(enum2));
    MyEnum enum3 = MyEnum.getByValue(4);
    System.out.println("enum3==>" + String.valueOf(enum3));
  }
}

enum MyEnum {
  Choice1(1), Choice2(2), Choice3(3);
  private static final Map<Integer, MyEnum> MY_MAP = new HashMap<Integer, MyEnum>();
  static {
    for (MyEnum myEnum : values()) {
      MY_MAP.put(myEnum.getValue(), myEnum);
    }
  }
  private int value;

  private MyEnum(int value) {
    this.value = value;
  }

  public int getValue() {
    return value;
  }

  public static MyEnum getByValue(int value) {
    return MY_MAP.get(value);
  }

  public String toString() {
    return name() + "=" + value;
  }

}

The code above generates the following result.