get enum name from enum value [duplicate]

2020-05-15 12:24发布

I've read a lot about how obtain the corresponding name of an enum from its value using java, but no example seems to work for me! What is wrong?

public class Extensions {


    public enum RelationActiveEnum
    {
        Invited(0),
        Active(1),
        Suspended(2);

        private final int value;

        private RelationActiveEnum(final int value) {
            this.value = value;
        }
    }

}

and in another class I use:

        int dbValue = supp.ACTIVE;
        Extensions.RelationActiveEnum enumValue(dbValue);
        String stringName = enumValue.toString(); //Visible
        // OR
        int dbValuee = supp.ACTIVE;
        String stringValue = Enum.GetName(typeof(RelationActiveEnum), dbValue);

I should work, right? but it doesn't!!!! it tells me that dbValue cannote be cast to RelationActiveEnum...

标签: java enums
7条回答
Rolldiameter
2楼-- · 2020-05-15 13:21

Say we have:

public enum MyEnum {
  Test1, Test2, Test3
}

To get the name of a enum variable use name():

MyEnum e = MyEnum.Test1;
String name = e.name(); // Returns "Test1"

To get the enum from a (string) name, use valueOf():

String name = "Test1";
MyEnum e = Enum.valueOf(MyEnum.class, name);

If you require integer values to match enum fields, extend the enum class:

public enum MyEnum {
  Test1(1), Test2(2), Test3(3);

  public final int value;

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

Now you can use:

MyEnum e = MyEnum.Test1;
int value = e.value; // = 1

And lookup the enum using the integer value:

MyEnum getValue(int value) {
  for(MyEnum e: MyEunm.values()) {
    if(e.value == value) {
      return e;
    }
  }
  return null;// not found
}
查看更多
登录 后发表回答