April 13, 2011

How to create initialized enum in Java.

One day I needed to create enum initialized to values other than its default values in Java. It can be done easily in C++. For example, look at the code below:

typedef enum ResponseType{
     OK = 200,
     TRYING = 100,
     RINGING = 180
} TResponseType;

However it is not so obvious in Java.

public enum ResponseType {
     OK(200),
     TRYING(100),
     RINGING(180),
     SESSION_PROGRESS(183),
     BAD_REQUEST(400),
     NOT_FOUND(404);

     private int value;

     ResponseType(int value){
           this.value = value;
     }

     public int getValue() {
          return value;
     }
};

No comments:

Post a Comment