猿问

Enum的values()方法的文档在哪里?

我将枚举声明为:


enum Sex {MALE,FEMALE};

然后,迭代枚举,如下所示:


for(Sex v : Sex.values()){

    System.out.println(" values :"+ v);

}

我检查了Java API,但找不到values()方法?我很好奇这种方法从哪里来?


API链接:https : //docs.oracle.com/javase/8/docs/api/java/lang/Enum.html


莫回无
浏览 768回答 3
3回答

慕娘9325324

您无法在javadoc中看到此方法,因为它是由编译器添加的。记录在三个地方:枚举类型,来自Java教程编译器在创建枚举时会自动添加一些特殊方法。例如,它们具有静态值方法,该方法将按声明顺序返回包含枚举的所有值的数组。此方法通常与for-each构造结合使用以迭代枚举类型的值。Enum.valueOf类(在values方法的描述中提到了特殊的隐式valueOf方法)可以通过调用该类型的隐式公共静态T [] values()方法来获取枚举类型的所有常量。枚举类型,第8.9节,Java语言规范该values函数仅列出枚举的所有值。

慕婉清6462132

该方法是隐式定义的(即由编译器生成)。从JLS:此外,如果E是enum类型的名称,则该类型具有以下隐式声明的static方法:/*** 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);
随时随地看视频慕课网APP

相关分类

Java
我要回答