意外的令牌 - Java 枚举

use*_*071 1 java enums

java中是否有任何选项可以创建具有 true 和 false 的枚举,如下所示,

public enum options {
true,
false,
both
}
Run Code Online (Sandbox Code Playgroud)

现在,当我使用 true 和 false 时出现意外的令牌错误。谢谢

问候哈鲁

Sil*_*olo 7

不可以。从JLS 8.9.1开始,枚举常量在语法中定义为

EnumConstant:
    {EnumConstantModifier} Identifier [( [ArgumentList] )] [ClassBody] 
Run Code Online (Sandbox Code Playgroud)

所以这是一个Identifier. 从JLS 3.8开始, 和Identifier被定义为

Identifier:
    IdentifierChars but not a Keyword or BooleanLiteral or NullLiteral 
Run Code Online (Sandbox Code Playgroud)

因此,标识符是任何有效的标识符字符字符串(基本上是字母和数字,但加入了 Unicode 支持),但不是关键字(例如if)或单词truefalsenull

实际上,无论如何你都应该将你的enum名字大写,所以它看起来更像

public enum Options {
  TRUE, FALSE, BOTH
}
Run Code Online (Sandbox Code Playgroud)

这不会造成任何问题,因为TRUEandFALSE不是 Java 中的布尔文字。