tags:

views:

139

answers:

4

Hi,

how to create the static enum like below

static enum Test{
 employee-id,
 employeeCode
}

as of now, i am getting error.

+7  A: 

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"

public enum Test
    EMPLOYEE_ID("employee-id");

    private Test(String realName) {
        this.realName = realName;
    }
    public String getRealName() {
        return realName;
    }
    private String realName;
}
DR
And use all-caps for enum constants.
Tom Hawtin - tackline
You should make realName final.
Steve Kuo
A: 

You cannot declare the enum constant with a hyphen. If you hyphen to be retrieved as the value of the enum, you should have a value method in enum which you either use in its toString method or access this method on the enum to get the hyphen value

Fazal
+1  A: 

You can not do this. Enum constants must be legal Java identifiers. Legal Java identifiers can not contain -. You can use _ if that's an acceptable substitute.

polygenelubricants
+2  A: 

This is not specific to enums. This applies to all identifiers in Java: class names, method names, variable names, etcetera. Hyphens are simply not allowed. You can find all valid characters in JLS 3.8.

To illustrate the problem:

int num-ber = 5;
int num = 4;
int ber = 3;

System.out.println(num-ber);

What would you expect to happen here?

BalusC