39
public class Constant {

  ......

  public enum Status {
    ERROR,
    WARNING,
    NORMAL
  }

  ......

}

After compiling I got a class file named Constant$Status.class. The question is, how can I access the enum value. For instance, I want to get the string representation of the ERROR status.

user207421
  • 305,947
  • 44
  • 307
  • 483
Terry Li
  • 16,870
  • 30
  • 89
  • 134

3 Answers3

52

You'll be able to access it elsewhere like

import package.name.Constant;
//...
Constant.Status foo = Constant.Status.ERROR;

or,

import package.name.Constant;
import package.name.Constant.Status;
//...
Status foo = Status.ERROR;

To get the declared name of any enum element, use Enum#name():

Status foo = ...;
String fooName = foo.name();
Matt Ball
  • 354,903
  • 100
  • 647
  • 710
6

In your code just do:

Constant.Status.ERROR.toString();
planetjones
  • 12,469
  • 5
  • 50
  • 51
2

Since this was not mentioned before, in the original question the enum has the public access modifier which means we should be able to do Constant.Status.ERROR.toString() from anywhere. If it was set to private it would have been available only to the class: Constant. Similarly it is accessible within the same package in case of no modifier (default).

AaCodes
  • 197
  • 1
  • 5