简体   繁体   English

Enum中的成员字段顺序

[英]Order of member fields in Enum

Why the order of declaration important for Java enums, I mean why does this give (compile time) errors 为什么声明的顺序对Java枚举很重要,我的意思是为什么这会给出(编译时)错误

public enum ErrorCodes {
    public int id;
    Undefined;
}

but this one is fine: 但是这个很好:

public enum ErrorCodes {
    Undefined;
    public int id;

}.

It's not a very satisfying answer, but it's just how enums are defined in Java. 这不是一个非常令人满意的答案,但它只是如何在Java中定义枚举。 See section 8.9 Enums in The Java Language Specification. 请参阅Java语言规范中的第8.9节“ 枚举 ”。

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 is a special kind of class. Java Enum是一种特殊的类。 Its simple and mostly useful form does not contain custom fields: 它简单且最有用的表单不​​包含自定义字段:

public enum ErrorCodes {
    Undefined, Defined, Foo, Bar
}

Compiler magic creates class that looks approximately like the following: 编译器魔术创建的类看起来大致如下:

public class ErrorCodes {
    public final static ErrorCodes Undefined = new ErrorCodes();
    public final static ErrorCodes Defined = new ErrorCodes();
    public final static ErrorCodes Foo = new ErrorCodes();
    public final static ErrorCodes Bar = new ErrorCodes();
}

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; Sun非常友好地允许我们添加遵循eunum成员定义的字段:public enum ErrorCodes {Undefined,Defined,Foo,Bar; private String myField; private String myField; } }

This is the reason that your custom code always must be defined after the enum fields. 这就是必须始终在枚举字段定义自定义代码的原因。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM