Enum.values()在哪里定义?

Dón*_*nal 8 java enums

每个Java枚举都有一个静态值()方法可以像这样使用

for (MyEnum enum : MyEnum.values()) {
    // Do something with enum
}
Run Code Online (Sandbox Code Playgroud)

但是,我无法弄清楚这个方法的定义.在Javadoc中没有提到它,它没有出现在源文件中的任何地方.

and*_*dri 10

这是Java语言规范所要求的:values并且valueOf将为所有枚举隐式声明:

/**
* Returns an array containing the constants of this enum 
* type, in the order they're declared.  This method may be
* used to iterate over the constants as follows:
*
*    for(E c : E.values())
*        System.out.println(c);
*
* @return an array containing the constants of this enum 
* type, in the order they're declared
*/
public static E[] values();

/**
* Returns the enum constant of this type with the specified
* name.
* The string must match exactly an identifier used to declare
* an enum constant in this type.  (Extraneous whitespace 
* characters are not permitted.)
* 
* @return the enum constant with the specified name
* @throws IllegalArgumentException if this enum type has no
* constant with the specified name
*/
public static E valueOf(String name);
Run Code Online (Sandbox Code Playgroud)

这些方法是在编译期间添加的,因此如果您使用javap反汇编代码,您实际上可以查看它们的正文.