Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a static enum with a value that has a hyphen symbol in Java?

Tags:

java

enums

how to create the static enum like below

static enum Test{
    employee-id,
    employeeCode
}

As of now, I am getting errors.

like image 218
coder Avatar asked Mar 22 '10 14:03

coder


1 Answers

This is not possible with Java, because each item has to be a valid identifier (and valid Java identifiers may not contain dashes).

The closest thing would be adding a custom property to each enum value or override the toString method, so you can do the following:

Test.EMPLOYEE_ID.getRealName();    // Returns "employee-id"
Test.EMPLOYEE_CODE.getRealName();  // Returns "employeeCode"

public enum Test
    EMPLOYEE_ID("employee-id"),
    EMPLOYEE_CODE("employeeCode");

    private Test(String realName) {
        this.realName = realName;
    }
    public String getRealName() {
        return realName;
    }
    private final String realName;
}
like image 112
Daniel Rikowski Avatar answered Sep 28 '22 06:09

Daniel Rikowski