繁体   English   中英

Enum.values() 在哪里定义?

[英]where is Enum.values() defined?

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

for (MyEnum enum : MyEnum.values()) {
    // Do something with enum
}

但是,我无法弄清楚此方法的定义位置。 Javadoc 中没有提到它,它也没有出现在源文件中的任何地方。

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

/**
* 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);

这些方法是在编译时添加的,所以如果用javap反汇编代码,其实可以看看它们的正文。

它没有明确定义,就像 java 数组的length属性没有定义一样。 它隐式可用于具体的 Enum 类型。

暂无
暂无

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

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