Enum 中成员字段的顺序
为什么声明的顺序对于 Java 枚举很重要,我的意思是为什么这会给出(编译时)错误,
public enum ErrorCodes {
public int id;
Undefined;
}
但这个很好:
public enum ErrorCodes {
Undefined;
public int id;
}.
Why the order of declaration important for Java enums, I mean why does this give (compile time) errors
public enum ErrorCodes {
public int id;
Undefined;
}
but this one is fine:
public enum ErrorCodes {
Undefined;
public int id;
}.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
因为这是枚举的语法。它可以允许不同的顺序,但这可能容易出现错误,例如忘记在字段上放置类型并将其转换为枚举值。
编辑:我说它们可以按任何顺序的原因是字段、方法、初始化程序和构造函数可以按任何顺序。我认为,如果是为了减少错误,这个限制是有效的。尽管字段/构造函数/方法可以按任何顺序排列,但为了可读性,按该顺序查看它们是很常见的。
Because this is the syntax for enums. It could allow different orders however this may have been open to mistakes such as forgetting to place a type on a field and turning it into a enum value.
EDIT: The reason I say they could be in any order is that fields, methods, initialisers and constructors can be in any order. I believe the restriction is valid if it is to reduce mistakes. Even though fields/constructors/methods can be in any order its very common to see them in that order for readability.
Java Enum 是一种特殊的类。它的简单且最有用的形式不包含自定义字段:
编译器魔术创建的类大致如下所示:
此编译器魔术期望字段定义紧接在枚举标头之后。
Sun 非常友善地允许我们添加遵循 enum 成员定义的字段:
公共枚举错误代码{
未定义、已定义、Foo、Bar;
私有字符串 myField;
这
就是您的自定义代码始终必须在枚举字段之后定义的原因。
Java Enum is a special kind of class. Its simple and mostly useful form does not contain custom fields:
Compiler magic creates class that looks approximately like the following:
This compiler magic expects the fields definition right after the enum header.
Sun were so kind to allow us to add such fields that follow the definition of eunum members:
public enum ErrorCodes {
Undefined, Defined, Foo, Bar;
private String myField;
}
This is the reason that your custom code always must be defined after the enum fields.
这不是一个非常令人满意的答案,但这就是 Java 中枚举的定义方式。请参阅《Java 语言规范》中的 8.9 枚举 部分。
It's not a very satisfying answer, but it's just how enums are defined in Java. See section 8.9 Enums in The Java Language Specification.