Java - How to add a special character to an enumeration?

I have a problem. I created SpecialCharacterField.java, an enumeration class that lists some special characters.

SpecialCharacterField.java

 package bp.enumfield; public enum SpecialCharacterField { +, #; } 

In my eclipse on line: public enum SpecialCharacterField{ error message appears: Syntax error, insert "EnumBody" to complete EnumDeclaration

Please, help. Thanks in advance.

+7
source share
3 answers

do something like that

 public enum SpecialCharacterField{ PLUS("+"), HASH("#"); private String value; private SpecialCharacterField(String value) { this.value = value; } public String toString() { return this.value; //This will return , # or + } } 
+9
source

These characters cannot be part of Java identifiers. Please note that the JVM itself does not impose such restrictions (only. /; And [is prevented), so you can use such names if you wrote the bytecode directly. However, this is usually an undesirable approach.

+5
source

enums can have fields and getter, like regular classes.

 public enum SpecialCharacterField{ Plus('+'), Hash('#'); private final char character; private SpecialCharacterField(char character) { this.character = character; } public char getCharacter() { return character; } } 

Note: Avoid overriding toString() - this is an anti-pattern: toString() is for human eyes only - you should not rely on it in code.

+3
source

All Articles