为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

莫回无 2019-11-06 10:59:06
我将枚举声明为: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
查看完整描述

3 回答

?
慕娘9325324

TA贡献1783条经验 获得超4个赞

您无法在javadoc中看到此方法,因为它是由编译器添加的。


记录在三个地方:


枚举类型,来自Java教程

编译器在创建枚举时会自动添加一些特殊方法。例如,它们具有静态值方法,该方法将按声明顺序返回包含枚举的所有值的数组。此方法通常与for-each构造结合使用以迭代枚举类型的值。


Enum.valueOf类

(在values方法的描述中提到了特殊的隐式valueOf方法)

可以通过调用该类型的隐式公共静态T [] values()方法来获取枚举类型的所有常量。


枚举类型,第8.9节,Java语言规范

该values函数仅列出枚举的所有值。


查看完整回答
反对 回复 2019-11-06
?
慕婉清6462132

TA贡献1804条经验 获得超2个赞

该方法是隐式定义的(即由编译器生成)。


从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);


查看完整回答
反对 回复 2019-11-06
  • 3 回答
  • 0 关注
  • 767 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信