Home > Back-end >  Get value from a Enum constant that is declared with value(s)
Get value from a Enum constant that is declared with value(s)

Time:07-12

I have the following Java enum:

public static enum ScheduleType {
        ONE("one"),
        SEC("sec"),
        THUR("thur");

        private ScheduleType() {
        }
    }

I need to figure out how I can get use this get value code:

....ScheduleType().getValue()

How I can implement getValue() method in order to get the value as String?

CodePudding user response:

public static enum ScheduleType {
    ONE("one"),
    SEC("sec"),
    THUR("thur");

    private final String value;

    private ScheduleType(String value) {
        this.value = value;
    }

    public String getValue() {
        return value;
    }
}

CodePudding user response:

Your enums just needs to have some private members to store the values and some public methods to access them from outside the enum.

here's some sample code from a project i'm working on -

public enum CitationFields {

    SUMMARY_TEXT("summary", 1), 
    SECTION_TEXT("section", 2);

    private final String fieldName;
    private final int sortOrder;


    CitationFields(String summary, int sortOrder) {
        this.fieldName = summary;
        this.sortOrder = sortOrder;
    }


    public String getFieldName() {
        return fieldName;
    }

    public int getSortOrder() {
        return sortOrder;
    }
}


int sortOrder = CitationFields.SUMMARY_TEXT.getSortOrder();
  •  Tags:  
  • java
  • Related