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

how to create a static enumeration as shown below

static enum Test{ employee-id, employeeCode } 

I am getting errors at the moment.

+8
java enums
source share
4 answers

This is not possible for Java, because each element must be a valid identifier (and valid Java identifiers may not contain dashes).

The immediate task would be to add a custom property for each enumeration 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 final String realName; } 
+17
source share

This does not apply to transfers. This applies to all identifiers in Java: class names, method names, variable names, and so on. Hyphens are simply not allowed. You can find all valid characters in the Java Language Specification, chapter 3.8 "Identifiers" .

To illustrate the problem:

 int num-ber = 5; int num = 4; int ber = 3; System.out.println(num-ber); 

What would you expect here?

+14
source share

You cannot do this. Enum constants must be legal Java identifiers. Java legal identifiers cannot contain - . You can use _ if this is an acceptable replacement.

+1
source share

You cannot declare a listing constant with a hyphen. If you are a hyphen in order to be obtained as an enumeration value, you must have a value method in the enumeration that you either use in the toString method, or refer to this method in the enumeration to get the hyphen value

0
source share

All Articles